Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store unique elements inside a JSONArray

Tags:

java

I am trying to store only unique elements fetched from Database inside a JSONArray

HashSet<String> hs = new HashSet<String>();
JSONArray mainarray=new JSONArray();

PreparedStatement stmt = connection.prepareStatement("SELECT * from categories");
ResultSet rs=stmt.executeQuery();

while(rs.next())
{
    String T1 = rs.getString("T1");
    hs.add(T1);
    if(!hs.contains(T1))
    {
        mainarray.put(T1);
    }
}


System.out.println(mainarray); 

Starngely the output is an empty array []

By the way i am using org.json.JSONArray.

Could anybody please help .


1 Answers

 hs.add(T1);
 if(!hs.contains(T1)) { ...

The condition will always be false ... because you just added the element!

Therefore you will never add anything to mainarray.


For what it is worth, here's a fix for your bug:

// Inelegant version
if (!hs.contains(T1)) {
    hs.add(T1);
    mainarray.put(T1);
}

// Elegant version that avoids two probes of the hashset
// ... see javadocs for `Set.add` to understand why this works.
if (hs.add(T1)) {
    mainarray.put(T1);
}
like image 182
Stephen C Avatar answered Apr 19 '26 09:04

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!