For strings this would work

arrayList.sort((p1, p2) -> p1.compareTo(p2));
Answer from poosliver on Stack Overflow
๐ŸŒ
Adeel
blog.adeel.io โ€บ 2016 โ€บ 10 โ€บ 16 โ€บ sorting-a-json-array-in-java
Sorting a JSON Array in Java โ€“ Adeel's Corner
October 16, 2016 - Letโ€™s start by converting a JSONArray to a Collection of JSONObjects, using the java List type: List<JSONObject> myJsonArrayAsList = new ArrayList<JSONObject>(); for (int i = 0; i < myJsonArray.length(); i++) myJsonArrayAsList.add(myJsonArray.getJSONObject(i));
๐ŸŒ
findnerd
findnerd.com โ€บ list โ€บ view โ€บ Sorting-JSONArray-in-java โ€บ 20597
Sorting JSONArray in java
June 3, 2016 - private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)"); public static JSONArray sortJson(JSONArray jsonArraylab,String type) { final String value=type; JSONArray sortedJsonArray = JSONFactoryUtil.createJSONArray(); List<JSONObject> jsonValues = new ArrayList<JSONObject>(); for (int i = 0; i < jsonArraylab.length(); i++) { jsonValues.add(jsonArraylab.getJSONObject(i)); } Collections.sort( jsonValues, new Comparator<JSONObject>() { //You can change "Name" with "ID" if you want to sort by ID private final String KEY_NAME = value; @Override public int compare(JSONObject a, JSONObje
Discussions

Sorting ArrayList with Lambda in Java 8 - Stack Overflow
Could somebody show me a quick example how to sort an ArrayList alphabetically in Java 8 using the new lambda syntax. More on stackoverflow.com
๐ŸŒ stackoverflow.com
android - How to sort array of json objects in java - Stack Overflow
so i want to sort in ascending order based on message id key. i tried with comparator with object type as json object, i am getting error in compareto method. please suggest me ... You're trying to do this the hardway. Either do it before you convert to JSON (if you're generating this), or after converting from JSON to java ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
json - How can I sort a JSONArray in JAVA - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Android how to sort JSONArray of JSONObjects - Stack Overflow
I have made a jsonarray of jsonobjects. Now I need to sort the JSONArray on base of a value from the jsonobjects. Formerly I sorted ArrayLists of custom objects like this: Comparators: public class More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Processing Foundation
discourse.processing.org โ€บ coding questions
Sorting a JSONArray by one of its values - Coding Questions - Processing Community Forum
November 28, 2019 - I have a JSONArray which saves โ€œNameโ€ and โ€œBestโ€. Best is always an int. I would like to be able to sort the array descending. I can not provide any code as there is none. Thanks in advance. String[] names = { "A", "B", "C" }; JSONArray values; void setup() { values = new JSONArray(); for (int i = 0; i
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-can-we-sort-a-jsonarray-in-java
How can we sort a JSONArray in Java?
The following is the example code that sorts a JSON array using the org.json library. import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortJsonArrayWithLibrary { public static void main(String[] args) { // Step 1: Create a JSON array JSONArray originalArray = new JSONArray(); originalArray.put(new JSONObject() .put("name", "Zara") .put("age", 28)); originalArray.put(new JSONObject() .put("name", "Alex") .put("age", 22)); originalArray.put(new JSONObject() .put("name"
Top answer
1 of 3
10

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;

    }
}
2 of 3
1

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);
}
Find elsewhere
Top answer
1 of 6
41

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

2 of 6
10

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;
}
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 26439821 โ€บ sorting-an-arraylist-of-jsonobjects-on-a-particular-json-element
java - Sorting an arraylist of jsonobjects on a particular json element - Stack Overflow
October 19, 2014 - Ive been looking at this answer (How to sort GSON Array based on a key?) but its not working for me. I have a custom class called Tracks.class which has all the getters and setters set up holding title,artist,genre etc ยท TrackFileManager.class is the serializer and where all the JsonObject.addProperty code is and returns a jsonObject back to MainActivity. this jsonObject then gets added to an ArrayList called values as below in MainActivity.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2023 โ€บ 10 โ€บ 6-ways-to-sort-arraylist-in-java.html
6 ways to sort ArrayList in Java 8? List.sort() + Collections.sort() Example Tutorial
October 4, 2023 - This is how objects are traditionally sorted in Java applications. From JDK 8, you can use List.sort() as preferred way to sort a list of objects. So far, we have seen examples of sorting ArrayList of objects in Java but on their natural order.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-sort-arraylist-in-java
How to Sort ArrayList in Java - javatpoint
How to Sort ArrayList in Java with java tutorial, features, history, variables, object, class, programs, operators, for-loop, oops concept, inheritance, array, string, map, math, methods, examples etc.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ sort-jsonarray-java
How to Sort a JSONArray in Java? - CodingTechRoom
Lack of methods in the JSONArray class to perform sorting. Convert the JSONArray to a List of JSONObject instances. Use Java Streams to sort the List based on the desired property (e.g., a field in the JSON object).
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2012 โ€บ 01 โ€บ how-to-sort-arraylist-in-java-example.html
How to sort ArrayList in Natural and Custom Order in Java - Example Tutorial
One of the best way to sort the ArrayList is by using List.sort() method which was added into List class in JDK 8. You can also pass it any custom comparator to sort the list in any custom order like the reverse order.
๐ŸŒ
Mysamplecode
mysamplecode.com โ€บ 2012 โ€บ 10 โ€บ java-sort-arraylist-of-objects.html
Java sort an ArrayList of objects - Programmers Sample Guide
package com.as400samplecode; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortArrayList { public static void main(String[] args) { SortArrayList sortArrayList = new SortArrayList(); sortArrayList.runExample(); } public void runExample(){ //create an ArrayList of employee objects ArrayList<Employee> employeeList = new ArrayList<Employee>(); Employee employee1 = new Employee("id1", "John", 10900); employeeList.add(employee1); Employee employee2 = new Employee("id2", "Ed", 10100); employeeList.add(employee2); Employee employee3 = new Employee
๐ŸŒ
Tpoint Tech
tpointtech.com โ€บ how-to-sort-arraylist-in-java
How to Sort ArrayList in Java - Tpoint Tech
February 19, 2026 - In Java, Collection is a framework that provides interfaces (Set, List, Queue, etc.) and classes (ArrayList, LinkedList, etc.
๐ŸŒ
Java Training School
javatrainingschool.com โ€บ home โ€บ how to sort an arraylist in java
How to sort an Arraylist in java - Java Training School
May 6, 2024 - Functional programming which was introduced in java 8 has made it very easy to sort arraylist using forEach method and lambda expression.
๐ŸŒ
Java67
java67.com โ€บ 2021 โ€บ 09 โ€บ 3-ways-to-sort-list-in-java-8-and-11.html
3 ways to sort a List in Java 8 and 11 - Example Tutorial | Java67
There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List.
๐ŸŒ
Java67
java67.com โ€บ 2017 โ€บ 07 โ€บ how-to-sort-arraylist-of-objects-using.html
How to Sort ArrayList of Objects by Fields in Java? Custom + Reversed Order Sorting Comparator Example | Java67
Btw, this is not the only way to sort an ArrayList of objects in Java. If you want you can use Comparable to sort in the natural order and in the decreasing order of natural order imposed by Comparator. the JDK 8 release also added a couple of methods on both java.util.Comparator class and java.util.List to make sorting easier.