For strings this would work
arrayList.sort((p1, p2) -> p1.compareTo(p2));
Answer from poosliver on Stack OverflowSorting ArrayList with Lambda in Java 8 - Stack Overflow
android - How to sort array of json objects in java - Stack Overflow
json - How can I sort a JSONArray in JAVA - Stack Overflow
java - Android how to sort JSONArray of JSONObjects - Stack Overflow
For strings this would work
arrayList.sort((p1, p2) -> p1.compareTo(p2));
Are you just sorting Strings? If so, you don't need lambdas; there's no point. You just do
import static java.util.Comparator.*;
list.sort(naturalOrder());
...though if you're sorting objects with a String field, then it makes somewhat more sense:
list.sort(comparing(Foo::getString));
I am posting the answer here helping others who are facing the issue with this kind of problems.
public static JSONArray getSortedList(JSONArray array) throws JSONException {
List<JSONObject> list = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i));
}
Collections.sort(list, new SortBasedOnMessageId());
JSONArray resultArray = new JSONArray(list);
return resultArray;
}
This part of the code will help to sort the json array
Check out the SortBasedOnMessageId class below.
public class SortBasedOnMessageId implements Comparator<JSONObject> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
* lhs- 1st message in the form of json object. rhs- 2nd message in the form
* of json object.
*/
@Override
public int compare(JSONObject lhs, JSONObject rhs) {
try {
return lhs.getInt("messageId") > rhs.getInt("messageId") ? 1 : (lhs
.getInt("messageId") < rhs.getInt("messageId") ? -1 : 0);
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Since Java 8 this can be solved with Integer.compare() function within 1 method:
private JSONArray getSortedMessages(JSONArray array) throws JSONException {
List<JSONObject> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i));
}
list.sort((a1, a2) -> {
try {
return Integer.compare(a1.getInt("messageId"), a2.getInt("messageId"));
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
});
return new JSONArray(list);
}
The issue is that JSONArray more or less holds JSONObjects (and other JSONArrays) which ultimately are strings. Deserializing the strings entirely into POJOs, sorting those, then back into JSON is fairly heavy.
The second issue is that a JSONArray can contain: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object; i.e. it is mixed types, making it hard to just dump the elements into a List of some type and sort that, then pass through the list dumping sorted items back into the JSON array. the only certain way to get a common type of each element from the JSONArray is using the Object get() method.. of course then all you have is Object objects and won't be able to do any meaningful sorting on them without revisiting the serialization issue.
Assuming your JSONArray contains homogeneously structured values, you could iterate through the JSONArray, calling one of the typed get() methods on each one, dumping them into a List type, then sorting on that. If your JSONArray just holds "simple" type like String or numbers, this is relatively easy. This isn't exact code but something like:
List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < myJsonArray.length(); i++)
jsonValues.add(myJsonArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);
Of course, if you have nested objects this can get a little trickier. If the value(s) you want to sort on live in the top level, it may not be soo bad...
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < myJsonArray.length(); i++)
jsonValues.add(myJsonArray.getJSONObject(i));
Then use a comparator like this to sort:
class JSONComparator implements Comparator<JSONObject>
{
public int compare(JSONObject a, JSONObject b)
{
//valA and valB could be any simple type, such as number, string, whatever
String valA = a.get("keyOfValueToSortBy");
String valB = b.get("keyOfValueToSortBy");
return valA.compareTo(valB);
//if your value is numeric:
//if(valA > valB)
// return 1;
//if(valA < valB)
// return -1;
//return 0;
}
}
Again, this makes some assumptions about the homogeneity of the data in your JSONArray. Adjust to your case if possible. Also you will need to add your exception handling, etc. Happy coding!
edit fixed based on comments
In order to fill up an Android list ArrayAdapter I needed to do just this. This is how I did it:
Activity code building a list from a JSONArray:
JSONArray kids = node.getJSONArray("contents");
kids = JSONUtil.sort(kids, new Comparator(){
public int compare(Object a, Object b){
JSONObject ja = (JSONObject)a;
JSONObject jb = (JSONObject)b;
return ja.optString("name", "").toLowerCase().compareTo(jb.optString("name", "").toLowerCase();
}
});
// in my case I wanted the original larger object contents sorted...
node.put("contents", kids);
And in JSONUtil (my helper):
public static JSONArray sort(JSONArray array, Comparator c){
List asList = new ArrayList(array.length());
for (int i=0; i<array.length(); i++){
asList.add(array.opt(i));
}
Collections.sort(asList, c);
JSONArray res = new JSONArray();
for (Object o : asList){
res.put(o);
}
return res;
}
Collections.sort(testList);
Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Here is the documentation for Collections.
Descending:
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});