Collection order by java

Java Sort List Collections Examples

In Java, it’s pretty easy to sort elements in a list collection using the Collections.sort() static utility method. This method has two forms as follows:

    • void sort(List list) : sorts the list into ascending order according to its elements’ natural ordering.
    • void sort(List list, Comparator c) : sorts the list into the order specified by the given comparator.
      • Fast: it guarantees O(n log n) performance in average and worst cases, and runs faster if the original list is nearly sorted.
      • Stable: it preservers the order the equal elements so it’s useful for sorting the list repeatedly on different attributes.

      Table of content:

      1. Sorting a list according to natural ordering of elements

      Basically, a list can be sorted if only all of its elements are mutually comparable by implementing the Comparable interface. If a class implements the Comparable interface, it is considered as having natural ordering which allows objects of that class to be sorted by the Collections.sort(list) method.

      All basic data type wrapper classes in Java have natural ordering: String, Character, Byte, Date, Integer, Float, etc. Here are some examples:

      Sorting a list of Strings:

      List listStrings = Arrays.asList("Orange", "Grape", "Apple", "Lemon", "Banana"); System.out.println("Before sorting: " + listStrings); Collections.sort(listStrings); System.out.println("After sorting: " + listStrings);
      Before sorting: [Orange, Grape, Apple, Lemon, Banana] After sorting: [Apple, Banana, Grape, Lemon, Orange]

      Sorting a list of Characters:

      List listCharacters = Arrays.asList('F', 'C', 'A', 'B', 'Z', 'E', 'K', 'P'); System.out.println("Before sorting: " + listCharacters); Collections.sort(listCharacters); System.out.println("After sorting: " + listCharacters);
      Before sorting: [F, C, A, B, Z, E, K, P] After sorting: [A, B, C, E, F, K, P, Z]
      List listIntegers = Arrays.asList(1, 6, 9, 3, 2, 0, 8, 4, 7, 5); System.out.println("Before sorting: " + listIntegers); Collections.sort(listIntegers); System.out.println("After sorting: " + listIntegers);
      Before sorting: [1, 6, 9, 3, 2, 0, 8, 4, 7, 5] After sorting: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

      Sorting a list of Dates:

      List listDates = new ArrayList(); DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); try < listDates.add(dateFormatter.parse("2013-09-30")); listDates.add(dateFormatter.parse("2013-07-06")); listDates.add(dateFormatter.parse("2013-11-28")); >catch (ParseException ex) < System.err.print(ex); >System.out.println("Before sorting: " + listDates); Collections.sort(listDates); System.out.println("After sorting: " + listDates);
      Before sorting: [Mon Sep 30 00:00:00 ICT 2013, Sat Jul 06 00:00:00 ICT 2013, Thu Nov 28 00:00:00 ICT 2013] After sorting: [Sat Jul 06 00:00:00 ICT 2013, Mon Sep 30 00:00:00 ICT 2013, Thu Nov 28 00:00:00 ICT 2013]

      2. Reversing sort order

      Because the sort(list) method always sorts the specified list into ascending order, so if we want to sort by descending order, we need to use the Collections.reverse(list) method in addition. For example:

      List listIntegers = Arrays.asList(1, 6, 9, 3, 2, 0, 8, 4, 7, 5); System.out.println("Before sorting: " + listIntegers); Collections.sort(listIntegers); System.out.println("After sorting: " + listIntegers); Collections.reverse(listIntegers); System.out.println("After reversing: " + listIntegers);
      Before sorting: [1, 6, 9, 3, 2, 0, 8, 4, 7, 5] After sorting: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After reversing: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

      NOTES: The reverse(list) method doesn’t sort the list, it just re-order the list’s elements in the reverse order. Therefore the list must be sorted using the sort(list) method before being reversed in order to have the list sorted in descending order.

      3. Sorting a list whose elements of a custom type

      What if a list contains elements of a custom type other than the pre-defined types above? Well, in that case, we have to make the class of the custom type implements the Comparable interface. Suppose that we have a custom type called Employee as follows:

      public class Employee < private String name; private int age; private int salary; public Employee(String name, int age, int salary) < this.name = name; this.age = age; this.salary = salary; >// getters and setters >

      If we try to sort a list whose elements of the type Employee above, the sort(list) method will throw a ClassCastException . Now, let’s the Employee class implemented the Comparable interface as follows:

      public class Employee implements Comparable  < // variables, getters and setters. @Override public int compareTo(Employee employee) < return employee.salary - this.salary; >>

      As we see, the Employee class now overrides the compareTo() method from the Comparable interface. This method simply compares the salary between this employee and another. And override the toString() method as follows:

      We override the toString() method of the Employee class so that the returned string will be used when printing the list content.

      The following code example creates a list of employees and sorts it based on the descending order of salary:

      List listEmployees = new ArrayList(); listEmployees.add(new Employee("Tom", 45, 80000)); listEmployees.add(new Employee("Sam", 56, 75000)); listEmployees.add(new Employee("Alex", 30, 120000)); listEmployees.add(new Employee("Peter", 25, 60000)); System.out.println("Before sorting: " + listEmployees); Collections.sort(listEmployees); System.out.println("After sorting: " + listEmployees);
      Before sorting: [(Tom, 45, 80000), (Sam, 56, 75000), (Alex, 30, 120000), (Peter, 25, 60000)] After sorting: [(Alex, 30, 120000), (Tom, 45, 80000), (Sam, 56, 75000), (Peter, 25, 60000)]

      4. Sorting a list using a Comparator

      The second form of the sort method takes a Comparator implementation that defines the ordering of elements in the list externally:

      Collections.sort(list, Comparator)

      In this case, the type of the elements need not implement the Comparable interface. This would be useful if we need to sort a list of custom objects which we cannot modify its class; or if we don’t want to rely on the natural ordering of the elements. The following code is example of a comparator that compares two employees based on their ages:

      package net.codejava.collections; import java.util.Comparator; /** * This comparator compares two employees by their ages. * @author www.codejava.net * */ public class EmployeeAgeComparator implements Comparator  < @Override public int compare(Employee emp1, Employee emp2) < return emp1.getAge() - emp2.getAge(); >>

      And the following code snippet sorts a list of employees using the above comparator:

      List listEmployees = new ArrayList(); listEmployees.add(new Employee("Tom", 45, 80000)); listEmployees.add(new Employee("Sam", 56, 75000)); listEmployees.add(new Employee("Alex", 30, 120000)); listEmployees.add(new Employee("Peter", 25, 60000)); System.out.println("Before sorting: " + listEmployees); Collections.sort(listEmployees, new EmployeeAgeComparator()); System.out.println("After sorting: " + listEmployees);
      Before sorting: [(Tom, 45, 80000), (Sam, 56, 75000), (Alex, 30, 120000), (Peter, 25, 60000)] After sorting: [(Peter, 25, 60000), (Alex, 30, 120000), (Tom, 45, 80000), (Sam, 56, 75000)]

      API References

      Other Java Collections Tutorials:

      About the Author:

      Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

      Add comment

      Comments

      l wish that l read this article before l did my homework assignment for java class online and it very useful article to know how compare and comparator work and also to know how to sort by age and data and so on.

      CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
      CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

      Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

      Источник

      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

      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

      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.

      Источник

      Читайте также:  Языки программирования ruby python
Оцените статью