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

// Use Collections.sort()
import java.util.*;
ArrayList<String> al = new ArrayList<String>();
al.add("teach");
al.add("sleep");
al.add("geek");
Collections.sort(al);//just pass any collection object reference
System.out.println(al);//output :- [geek,sleep,teach]

or
/*
ArrayList<Integer> intal = new ArrayList<Integer>();
al.add(4);
al.add(8);
al.add(2);
Collections.sort(intal);
System.out.println(intal);//output :- [2,4,8]
*/

Example 3: java sort method

Arrays.sort();//this method is an inbuild function in java
//to sort the array

Example 4: java array sort by element

//sort array of array of integer by the second element;
int[][] array = new int[m][2];
//initialize array
Arrays.sort(array, (a,b)-> Integer.compare(a[1], b[1]));

Tags:

Java Example