2

I have a JSONArray as below,

JSONArray dataArray = new JSONArray();
dataArray = [
    {
        "name": "name1",
        "row": 1,
        "value": 20
    },
    {
        "name": "name2",
        "row": 1,
        "value": 10
    },
    {
        "name": "name3",
        "row": 2,
        "value": 10
    },
    {
        "name": "name4",
        "row": 3,
        "value": 30
    },
    {
        "name": "name5",
        "row": 3,
        "value": 10
    }
]

I need to compare the row attribute, if same, need to compare value attribute and sort the object in the array.

Tried with Java comparator, but couldn't make it work. Can somebody please help?

            
   for(int i = 0; i < dataArray.size(); i++) {
       elementList.add((JSONObject) dataArray.get(i));
   }
   Long row1 = null;
   for (JSONObject obj : elementList) {
       if(row1 == null) {
           row1 = (Long) ((JSONObject) obj.get("row"));
       }
       else {
            Long row2 = (Long) ((JSONObject) obj.get("row"));
            if(row2 == row1) {
                //call the comparator, but how to pass two objects?
            }
            row1 = row2;
       }
   }
Sunil C N
  • 33
  • 6

3 Answers3

2

It would be easy to extend this answer to match your scenario

But instead of

 return valA.compareTo(valB);

you should do

     int comp = valA.compareTo(valB);
        if (comp == 0){
            String valC = (String) a.get(KEY_NAME2);
            String valD = (String) b.get(KEY_NAME2);
            return valC.compareTo(valD);
        } else {
            return comp;
        }

So it should be the following.

    JSONArray sortedJsonArray = new JSONArray();
    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    for (int i = 0; i < dataArray.length(); i++) {   // <---- dataArray is the input that you have
        jsonValues.add(dataArray.getJSONObject(i));
    }
    Collections.sort( jsonValues, new Comparator<JSONObject>() {
        //You can change "Name" with "ID" if you want to sort by ID
        private static final String KEY_NAME1 = "row";
        private static final String KEY_NAME2 = "value";

        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = (String) a.get(KEY_NAME1);
                valB = (String) b.get(KEY_NAME1);
            }
            catch (JSONException e) {
                //do something
            }

            int comp = valA.compareTo(valB);
            if (comp == 0){
                String valC = (String) a.get(KEY_NAME2);
                String valD = (String) b.get(KEY_NAME2);
                return valC.compareTo(valD);
            } else {
                return comp;
            }
        }
    });

Edit: changed into KEY_NAME1 = "row"; to match the new question requirement

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
  • This worked! Thank you. I had to change `String` to `Integer` and `Long`. I see the Objects sorted now!! – Sunil C N Apr 28 '22 at 07:44
1

A simpler approach here:

You could convert your JSON string to List<YourObject> by using Jackson's ObjectMapper

List<YourObject> list = objectMapper.readValue(json, new TypeReference<List<YourObject>>(){});

Then use Collections.sort and Comparator to sort this list. You can also implement a custom Comparator to sort a list by multiple attributes depending on your situation.

list.sort(Comparator.comparing(YourObject::getRow)
    .thenComparing(YourObject::getValue));
Kai-Sheng Yang
  • 1,535
  • 4
  • 15
  • 21
0

Let's assume you deserialize your json data into objects like

public class DataRow {
    private String name;
    private int row;
    private int value;
    // Getter, Setter, Constructor what ever needed
}

Then you can work with a list and stream like:

List<DataRow> datarows = //... read data from json

List<DataRow> sorted = datarows.stream()
    .sorted(Comparator.comparing(DataRow::getRow).thenComparingInt(DataRow::getValue)).toList();
Crude Code
  • 137
  • 1
  • 9