Java Collections.Sort doesn't / can't group by same value
enter image description here
my code is :
excelSheetRows -> existing JSONArray data.
JSONArray sortedJsonArray = new JSONArray();
List list = new ArrayList();
for(int i = 0; i < excelSheetRows.length(); i++) {
list.add(excelSheetRows.getJSONObject(i));
}
Collections.sort(list, new Comparator() {
public int compare(JSONObject a, JSONObject b) {
// TODO Auto-generated method stub
String str1 = new String();
String str2 = new String();
try {
str1 = (String)a.get(KEY_NAME);
str2 = (String)b.get(KEY_NAME);
} catch(JSONException e) {
e.printStackTrace();
}
return str1.compareTo(str2);
}
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
return 0;
}
});
for(int i = 0; i < excelSheetRows.length(); i++) {
sortedJsonArray.put(list.get(i));
}
It ran successfully, but the sortedJsonArray doesn't group the same name together, example:
a20190510 a20190529 a20190626 a20190510
vincent vincent vinagent33 vincent vincent2222 vincent
please adviceeeee, i need all 'vincent' or 'a20190510' to be together, need ascending order group by same name, why it doesnt group by name accordingly???
Solution 1:
The problem is you're initializing the list without any type. See this answer for more explanation.
If you do List list = new ArrayList()
your list will contain implementations of 'Object', therefore when you sort you will use the comparator with Objects, that you didn't define.
To solve your issue, just define the type in the list:
List<JSONObject> list = new ArrayList<>();
You also need to define the type in the comparator:
Collections.sort(list, new Comparator<JSONObject>(){...}):
In this way the sorting algorithm will use the compare method that you defined.
Moreover, I can suggest you to make the code much more simple, you can in fact sort it with just one line if you use lambda functions:
list.sort(Comparator.comparing(json -> json.get(KEY_NAME));