Java sort object in arraylist

Java ArrayList sort()

The sort() method sorts the elements in an arraylist according to the specified order.

Example

import java.util.ArrayList; import java.util.Comparator; class Main < public static void main(String[] args) < // create an ArrayList ArrayListnumbers = new ArrayList<>(); numbers.add(7); numbers.add(3); numbers.add(9); numbers.add(-33); System.out.println("Unsorted ArrayList: " + numbers); // sort the ArrayList in ascending order 
numbers.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + numbers); > > // Output: Unsorted ArrayList: [7, 3, 9, -33] // Sorted ArrayList: [-33, 3, 7, 9]

Syntax of ArrayList sort()

The syntax of the sort() method is:

arraylist.sort(Comparator c)

Here, arraylist is an object of the ArrayList class.

sort() Parameters

The sort() method takes a single parameter.

sort() Return Values

The sort() method does not return any value. Rather it only changes the order of elements in an arraylist.

Example 1: Sort the ArrayList in Natural Order

import java.util.ArrayList; import java.util.Comparator; class Main < public static void main(String[] args) < // create an ArrayList ArrayListlanguages = new ArrayList<>(); // add elements to ArrayList languages.add("Python"); languages.add("Swift"); languages.add("C"); languages.add("JavaScript"); System.out.println("Unsorted ArrayList: " + languages); // sort the ArrayList in ascending order 
languages.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + languages); > >
Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [C, JavaScript, Python, Swift]

In the above example, we have used the sort() method to sort the arraylist named languages. Notice the line,

languages.sort(Comparator.naturalOrder());

Here, the naturalOrder() method of the Java Comparator Interface specifies that elements are sorted in natural order (i.e. ascending order).

The Comparator interface also provides a method to sort elements in descending order. For example,

Example 2: Sort the ArrayList in Reverse Order

import java.util.ArrayList; import java.util.Comparator; class Main < public static void main(String[] args) < // create an ArrayList ArrayListlanguages = new ArrayList<>(); // add elements to ArrayList languages.add("Python"); languages.add("Swift"); languages.add("C"); languages.add("JavaScript"); System.out.println("Unsorted ArrayList: " + languages); // sort the ArrayList in ascending order 
languages.sort(Comparator.reverseOrder());
System.out.println("Sorted ArrayList: " + languages); > >
Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [Swift, Python, JavaScript, C]

Here, the reverseOrder() method of the Comparator interface specifies that elements are sorted in reverse order (i.e. descending order).

Note: The Collections.sort() method is the more convenient method for sorting an arraylist.

Источник

Java Collections sort()

Learn to use Collections.sort() method to sort a list of objects using some examples.

By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections.reverseOrder() method, which returns a Comparator, for reverse sorting.

1. Sorting in Natural Order and Reverse Order

Читайте также:  Ide for javascript eclipse

Collections.sort(list); //Sorts in natural order Collections.sort(list, Collections.reverseOrder()); //Sorts in reverse order
  1. Above method sorts the specified list of items into their natural order.
  2. All items must implement the Comparable interface.
  3. All items must be mutually comparable and should not throw ClassCastException .
  4. This sort is guaranteed to be stable. It means that equal elements will not be reordered as a result of the sort.
  5. The specified list must be modifiable, but need not to be resizable.
  6. The sort() does not return any value.

1.1. Sorting an ArrayList of Strings

Java program to sort a list of strings lexicographically (in the dictionary order).

List names = Arrays.asList("Alex", "Charles", "Brian", "David"); //Prints - [Alex, Brian, Charles, David] Collections.sort(names); //Prints - [David, Charles, Brian, Alex] Collections.sort(names, Collections.reverseOrder()); 

1.2. Sorting ArrayList of Objects by Field

We may require to sort a list of custom objects which can have their own sorting logic. In this case, implement the Comparator interface in the custom class.

For example, the domain object Employee has default sorting on the name field. Checkout for comparison logic in compareTo() method.

public class Employee implements Comparable < private Integer id; private String name; private String email; private LocalDate dateOfBirth; //Getters and Setters @Override public int compareTo(Employee e) < return this.getName().compareTo(e.getName()); >>

Nest Java program sorts the list of Employee objects by their name;

ArrayList employees = methodReturnsUnsortedList(); //Narutal order sorting Collections.sort(employees); //Reverse sorting Collections.sort(employees, Collections.reverseOrder());

2. Custom Sorting using Comparators

The second parameter in sort() method takes an instance of Comparator .

We can implement any kind of comparison logic with the help of comparators and then we can use sort() method to sort the list based on the given custom logic.

Collections.sort(List, Comparator);

We can create a separate Comparator instances for each kind of sorting need, and then we can combine those instances to create group sorting effect.

For example, if we want to sort the Employee list on three fields – id, name, and age. In this case, we need to create 3 Comparator instances.

2.1. Creating Custom Comparator

This is general syntax to create a Comparator in Java. In this case, we are creating a Comparator which will sort the Employee list by id field.

Comparator compareById = new Comparator() < @Override public int compare(Employee o1, Employee o2) < return o1.getId().compareTo(o2.getId()); >>; Comparator compareByName = new Comparator() < @Override public int compare(Employee o1, Employee o2) < return o1.getName().compareTo(o2.getName()); >>;

We can use lambda expression for further shortening the syntax.

//Id Comparator Comparator compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() ); //Name Comparator Comparator compareByName = (Employee o1, Employee o2) -> o1.getName().compareTo( o2.getName() );

2.2. Using Comparator for Sorting

Читайте также:  Parallel computation in python

ArrayList employees = getUnsortedEmployeeList(); Comparator compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() ); Collections.sort(employees, compareById); Collections.sort(employees, compareById.reversed());

In the above code examples, we learned to sort an ArrayList in default order or reverse order.

We also learned to use the Comparators for implementing the custom sorting logic.

Источник

How to sort ArrayList in Java? Examples

Sorting ArrayList in Java is not difficult; by using the Collections.sort() method, you can sort ArrayList in ascending and descending order in Java. The Collections.sort() the method optionally accepts a Comparator. If provided, it uses Comparator’s compare method to compare Objects stored in Collection to compare with each other; in case of no explicit Comparator, Comparable interface’s compareTo() method is used to compare objects from each other. If objects stored in ArrayList don’t implement Comparable, they can not be sorted using the Collections.sort() the method in Java.

How to Sort An ArrayList in Java with Examples

Here is a complete code example of How to sort ArrayList in Java; in this Sorting, we have used Comparable method of String for sorting String on their natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering like in reverse order by using Collections.reverseOrder() or insensitive order by using String.CASE_INSENSITIVE_COMPARATOR .

1.1 Sorting ArrayList in Ascending Order in Java

First, let’s see how to sort an array in ascending order in Java using the Collections.sort() method. This method is overloaded, which means you can sort the ArrayList in natural order by leveraging the default comparator, which sorts the list in the natural order, and you can use the Collections.sort(list, Comparator) to sort the ArrayList in custom order defined by Comparator.

Since we are sorting ArrayList of String which implements a Comparable method, we can use the first method to sort the ArrayList string into the natural order or ascending order. You can also use this method to sort an ArrayList of Integer into increasing order because that’s the default order for an Integer object.

import java.util.*; class Main < public static void main(String[] args) < ListlistofYears = new ArrayList(); listofYears.add(2021); listofYears.add(2019); listofYears.add(2018); listofYears.add(2020); // print the ArrayList before sorting System.out.println("ArrayList before sorting"); System.out.println(listofYears); // sorting an ArrayList of Integer in ascending order Collections.sort(listofYears); // print the ArrayList after sorting System.out.println("ArrayList after sorting"); System.out.println(listofYears); > >
Output: java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main ArrayList before sorting [2021, 2019, 2018, 2020] ArrayList after sorting [2018, 2019, 2020, 2021]

1.2 Sorting ArrayList in Descending Order in Java

Now that you know how to sort ArrayList in ascending order, it’s time to sort the given ArrayList into descending order. For that, we’ll use the overloaded version of the Collections.sort() method, which accepts a Comparator.

Читайте также:  Tkcalendar python 3 документация

Don’t worry, you don’t need to create your own Comparator; in fact, you can use the Collections.reverseOrder() method, which returns a reverse order comparator that can be used to sort an ArrayList on descending order in Java.

import java.util.*; class Main < public static void main(String[] args) < ListlistofYears = new ArrayList(); listofYears.add(2021); listofYears.add(2019); listofYears.add(2018); listofYears.add(2020); // print the ArrayList before sorting System.out.println("ArrayList before sorting"); System.out.println(listofYears); // sorting an ArrayList of Integer in descending order Collections.sort(listofYears, Collections.reverseOrder()); // print the ArrayList after sorting System.out.println("ArrayList after sorting"); System.out.println(listofYears); > >
java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main ArrayList before sorting [2021, 2019, 2018, 2020] ArrayList after sorting [2021, 2020, 2019, 2018]

How to sort ArrayList in Java? Examples

1.3 Java Program to Sort an ArrayList of String in Java

Now that you know the mechanism to sort an ArrayList of objects into both ascending and descending order, it’s time to take a look at the complete Java program, which you can copy-paste in your Eclipse or IntelliJIDEA IDEA and run it. You can also save this in a Java source file and run it from the command prompt.

import java.util.ArrayList ;
import java.util.Collections ;
/**
*
* Java program to demonstrate How to sort ArrayList in Java

* core Java libraries.
*
* @author Javin
*/
public class CollectionTest

public static void main ( String args [])

//Creating and populating ArrayList in Java for Sorting
ArrayList < String > unsortedList = new ArrayList < String > () ;

unsortedList. add ( «Java» ) ;
unsortedList. add ( «C++» ) ;
unsortedList. add ( «J2EE» ) ;

System. err . println ( «unsorted ArrayList in Java : » + unsortedList ) ;

//Sorting ArrayList in ascending Order in Java
Collections. sort ( unsortedList ) ;
System. out . println ( «Sorted ArrayList in Java — Ascending order : » + unsortedList ) ;

//Sorting ArrayList in descending order in Java
Collections. sort ( unsortedList, Collections. reverseOrder ()) ;
System. err . println ( «Sorted ArrayList in Java — Descending order : » + unsortedList ) ;
>
>
Output:
unsorted ArrayList in Java : [ Java, C++, J2EE ]
Sorted ArrayList in Java — Ascending order : [ C++, J2EE, Java ]
Sorted ArrayList in Java — Descending order : [ Java, J2EE, C++ ]

That’s all on How to Sort ArrayList in Java in both ascending and descending order. Just remember that Collections.sort() will sort the ArrayList in ascending order, and if you provide a reverse comparator, it will sort the ArrayList in descending order in Java.

Источник

Оцените статью