0

Following Json needs to group by city to get array along with count if city have same array value. after that I want to sort the 2 biggest and the rest are added together, but how to do it?

{
"data": [
        {
            "ID": 47,
            "city": "Jakarta"
        },
        {
            "ID": 48,
            "city": "Bogor"
        },
        {
           "ID": 49,
            "city": "Bogor"
        },
        {
            "ID": 50,
            "city": "Jakarta"
        },
        {
            "ID": 51,
            "city": "Jakarta"
        },
        {
            "ID": 52,
            "city": "Bali"
        },
        {
            "ID": 50,
            "city": "Lampung"
        }
    ]
}

and i have tried so far is group by city to get array

try {
        JSONObject jsonObject = new JSONObject(result);
        HashMap<String,Integer> hashMap = new HashMap<>();
        for (int i=0;i<jsonObject.getJSONArray("data").length();i++){
            JSONObject innerJsonObject = jsonObject.getJSONArray("data").getJSONObject(i);
            String key = innerJsonObject.getString("city");
            if(hashMap.containsKey(key)){
                int count = hashMap.get(key)+1;
                hashMap.put(key,count);
            }else {
                hashMap.put(key,1);
            }
        }
        Log.e("Hashmap---",hashMap.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

and the result is :

  • Bogor = 2
  • Jakarta = 3
  • Bali = 1
  • Lampung = 1

the expected result is :

  • Jakarta = 3

  • Bogor = 2

  • Another city = 2

rangga ario
  • 19
  • 1
  • 8

1 Answers1

0

Try to add that HashMap into TreeMap after the for loop like this

     Map<String, Integer> reverseSortedMap = new TreeMap<String, 
        Integer>(Collections.reverseOrder());

      reverseSortedMap.putAll(hashMap);//your hashMap with count of city

      System.out.println("Reverse Sorted Map   : " + reverseSortedMap);