Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Here is the documentation for Collections.

Answer from tckmn on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_arraylist_sort.asp
Java ArrayList sort() Method
Non-primitive types must implement Java's Comparable interface in order to be sorted without a comparator. ... import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.sort( (a, b) -> { return -1 * a.compareTo(b); } ); System.out.println(cars); } }
Discussions

How can I sort an arrayList containing objects without using a sort method from the java collections library?
https://en.wikipedia.org/wiki/Selection_sort#Implementations Translate that to Java. More on reddit.com
๐ŸŒ r/learnprogramming
21
2
June 25, 2022
Sorting an ArrayList of objects by their attribute of type double in Java/OOP
I tried to use Arrays.sort for the first time but I'm not really getting anywhere. What does "not really getting anywhere" mean? What specifically did you try, and what didn't work? You'll need to create a custom Comparator object and pass it to sort in order to define what order the values should be sorted in. More on reddit.com
๐ŸŒ r/learnprogramming
6
4
October 9, 2022
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ api โ€บ system.collections.arraylist.sort
ArrayList.Sort Method (System.Collections) | Microsoft Learn
Sorts the elements in a range of elements in ArrayList using the specified comparer. public: virtual void Sort(int index, int count, System::Collections::IComparer ^ comparer);
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-sort-an-arraylist
Java Program to Sort an ArrayList - GeeksforGeeks
July 23, 2025 - The syntax for the sort() method is like below. ... All elements in the ArrayList must be mutually comparable, else it throws ClassCastException.
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ daniel sutantyo
CP-1.010 Java Tutorial - Sorting an ArrayList - YouTube
Problem: Sort of Sorting (https://open.kattis.com/problems/sortofsorting)In this video I discuss how you can sort an ArrayList. In case you haven't used an A...
Published: September 14, 2021
Views: 3K
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ java โ€บ arraylist โ€บ .sort()
Java | ArrayList | .sort() | Codecademy
January 5, 2024 - The .sort() method is used to sort arrays of primitive types and objects.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how can i sort an arraylist containing objects without using a sort method from the java collections library?
r/learnprogramming on Reddit: How can I sort an arrayList containing objects without using a sort method from the java collections library?
June 25, 2022 -

I have this code I am working on for a homework assignment, but the professor has specified that we cannot use anything from java collections. The issue is that all of his examples use collections, and all of his examples about sorting only cover sorting an int array. The code I am writing has to sort the array by both "rollno"(the int variable assigned to each "student" object) and by "name"(the string variable assigned to each "student").

The assignment calls for the use of a selection sort method, so I want to sort the numbers in order from 1-10 and sort the names by string length. If anyone can guide me forward on this I would greatly appreciate it because I am lost on how to even begin a selection sort method.

Sidenote: The github has four files in it; "arrSort", "Student", "rollComp", and "nameComp". "arrSort" is the main method and is where I am trying to implement the sort method, "Student" is the object class, "rollComp" and "nameComp" are both comparator classes. All of these files are copied directly from my IDE, and if you notice ANY errors in how I have formatted anything, or if you have any other questions please let me know.

๐ŸŒ
Spring Framework Guru
springframework.guru โ€บ home โ€บ sorting arraylists in java: a practical guide
Sorting ArrayLists in Java: A Practical Guide - Spring Framework Guru
October 22, 2024 - Sorting ArrayList objects is a common task that can be accomplished in several ways. We can sort ArrayLists using the simple Collections.sort() method, or more advanced techniques using custom comparators, lambdas, and the Stream API.
Top answer
1 of 16
1737

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since java-8

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

2 of 16
202

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

Two examples:

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

Usage:

List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);

List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());

// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
    public int compare(Chair chair1, Chair chair2) {
        ...
    }
});
๐ŸŒ
Vultr
docs.vultr.com โ€บ java โ€บ standard library โ€บ java โ€บ util โ€บ arraylist โ€บ sort()
Java ArrayList sort() - Order Elements
November 15, 2024 - This code snippet initializes an ArrayList with integers, then sorts them in ascending order.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ collections framework โ€บ java arraylist โ€บ java arraylist sort: ascending and descending order
Java ArrayList Sort: Ascending and Descending Order
August 4, 2023 - For specific cases, it is good to know the requirements and use the customized solution: Implement Comparable interface for natural ordering, and use Comparator instances for custom and reverse ordering ยท Use List.sort() if we want to modify ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ sorting an arraylist of objects by their attribute of type double in java/oop
r/learnprogramming on Reddit: Sorting an ArrayList of objects by their attribute of type double in Java/OOP
October 9, 2022 -

How's it going everyone?

I need some help in this. So I have this method below that works fine and basically prints the toString representation of different employees by going through each one in the Arraylist of employees objects called Company. Employees are objects with the following attributes: ID, name and gross salary. Now I have to create another method that does the same thing pretty much, but this time prints the toString of my employees by ascending order sorted by the gross salary of employees which is a method I have called getEmployeeGrossSalary() because i'm using encapsulation. I tried to use Arrays.sort for the first time but I'm not really getting anywhere. Anyone could give some hints or has a simple plan for me to implement this?

N.B: My method to create has to return a String which is the toStrings of the employees in my Company ArrayList otherwise I would have problems in the testings my professor made.

Always appreciative of your help <3

//From my company class

public String printAllEmployees(){

        StringBuilder printEmployees = new StringBuilder();

        for (Employee employee : Company){
            printEmployees.append(employee.toString()).append("\n");

        } return "All registered employees: \n" + printEmployees;
    }

//From my employee class

public String toString() {
            String grossSalaryTruncated = 
String.format("%.2f",this.getEmployeeGrossSalary());
            return this.getEmployeeName() + "'s gross salary is " + grossSalaryTruncated + " USD per month.";
        }

Ended up with this (below) and it worked somehow xD. Can someone just explain how it is working? I'm not really familiar with the syntax..

public String printSortedEmployees() {

    StringBuilder printSortedEmps = new StringBuilder();

    Company.sort(Comparator.comparingDouble(Employee::getEmployeeGrossSalary));
    for (Employee employee : Company) {
        printSortedEmps.append(employee.toString()).append("\n");

    }
    return "Employees sorted by gross salary (ascending order): \n" + printSortedEmps;
}
๐ŸŒ
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 - In this example, c1, c2 represent Cricketer class objects and sorting is done on a property called name which is String data type. Refer the full example below. ... package com.jts; public class Cricketer { private String name; private int noOfRuns; //getter and setters //constructors //toString } ... package com.jts; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArraylistSortingExample { public static void main(String[] args) { List<Cricketer> cList = new ArrayList<>(); cList.add(new Cricketer("Virat Kohli", 10000)); cList.add(new Cricketer("Roh
๐ŸŒ
PrepBytes
prepbytes.com โ€บ home โ€บ java โ€บ arraylist sort in java
ArrayList Sort in Java
September 22, 2023 - ArrayList Sort in Java can be performed to sort the ArrayList in ascending or descending order with a condition that there are no elements of different types such that all of them are mutually comparable to each other.
๐ŸŒ
Medium
medium.com โ€บ @er.pankajsonagara โ€บ java-how-do-you-sort-an-arraylist-in-descending-order-57b3a5c2935e
Java: How do you sort an ArrayList in descending order? | by Pankaj Sonagara | Medium
April 9, 2024 - Letโ€™s say List of Student class and you want to sort by name. See the code for both scenario. ... import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayListSort1 { public static void main(String[] args) { List list = new ArrayList<>(Arrays.asList(new Long[] { 50l, 4l, 10l, 1l, 2l, 3l })); System.out.println("Before Short"); System.out.println(list); System.out.println("After Short"); list.sort(Collections.reverseOrder()); System.out.println(list); } }
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-sort-a-list-in-java
How to Sort a List in Java โ€“ Java List Sorting Example
January 24, 2023 - Here is an example of how to use the Collections.sort() method to sort a list of integers: import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args) { List<Integer> ...