Home > OS >  Java - sort JSONArray based on two attribute values
Java - sort JSONArray based on two attribute values

Time:04-29

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;
       }
   }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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