Home > OS >  Find unique values in list of JSON objects
Find unique values in list of JSON objects

Time:03-24

Say I have a list of JSON Objects, like so:

List<JSONObject> listOfJSON Objects = new ArrayList<>();

{
    "key1": apple
    "key2": banana
    "key3": orange
}
{
    "key1": melon
    "key2": banana
    "key3": orange
}    
{
    "key1": apple
    "key2": grape
    "key3": strawberry
}

All the keys in each JSON Object in the list will be the exact same, in the same order even. I need to find each of the unique values and map it to each key so the end result will be:

{
    "key1": [apple, melon]
    "key2": [banana, grape]
    "key3": [strawberry, orange]
}

And if possible, I'd like to append the count for each at the end of each one so ideal result would be:

{
    "key1": [apple (2), melon (1)]
    "key2": [banana (2), grape (1)]
    "key3": [strawberry (1), orange (2)]
}

CodePudding user response:

For your first question, you can use data model like a Map<String, Set> where the key is the JSON key and the Set will take all your JSON values. Duplicates will be ignored as that's how the Set data model works. Then, simply iterate through your JSON objects and their properties and populate your Map.

For your second question, you can use Map<String, Map<String, Integer>. As you iterate simply get (or create, if not found) record from the first map using the JSON key, and then get (or create, if not found) the record from the inner map by the JSON property value. Increment the Integer by 1 in the record existed, otherwise use value 1.

  • Related