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;
       }
   }
2
  • Your code is not valid Java, can you show some example code that compiles and runs? Commented Apr 28, 2022 at 7:13
  • 2
    "Tried with Java comparator, but couldn't make it work." please edit your question to include your attempt, so we can start from that. Commented Apr 28, 2022 at 7:14

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

This worked! Thank you. I had to change String to Integer and Long. I see the Objects sorted now!!
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));

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.