java sort.by code example
Example 1: sort list of objects by attribute java
ArrayList<Employee> employees = getUnsortedEmployeeList();
Comparator<Employee> compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() );
Collections.sort(employees, compareById);
Collections.sort(employees, compareById.reversed());
Example 2: how to sort collection in java
import java.util.*;
ArrayList<String> al = new ArrayList<String>();
al.add("teach");
al.add("sleep");
al.add("geek");
Collections.sort(al);
System.out.println(al);
or
Example 3: java sort method
Arrays.sort();
Example 4: java array sort by element
int[][] array = new int[m][2];
Arrays.sort(array, (a,b)-> Integer.compare(a[1], b[1]));