want to sort a list in java with Lambda? Here is how:
class Person { private Integer age; private String name; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(Integer age, String name) { super(); this.age = age; this.name = name; } @Override public String toString() { return "Person [age=" + age + ", name=" + name + "]"; } }
package com.leespace.java8; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class JavaLambdaSort { public static void main(String[] args) { List <Person> people= getArrayList(); //Sort by name in traditional way with Comparator: Collections.sort(people, new Comparator <Person> () { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } }); displayList(people); //Sort by name in traditional way with Comparator: Collections.sort(people, new Comparator <Person> () { @Override public int compare(Person p1, Person p2) { return p1.getAge().compareTo(p2.getAge()); } }); displayList(people); //Sort by name in with lambda: Collections.sort(people, (p1,p2) -> p1.getName().compareTo(p2.getName())); displayList(people); //Sort by age in with lambda: Collections.sort(people, (p1,p2) -> p1.getAge().compareTo(p2.getAge())); displayList(people); } private static void displayList(List<Person> people) { System.out.println("\nThe sorted list:"); for (Person p:people) { System.out.println(p); } } private static List<Person> getArrayList() { List<Person> people = new ArrayList<Person>(); Person person1 = new Person(21, "Jack Lee"); people.add(person1); Person person2 = new Person(31, "Jack Ma"); people.add(person2); Person person3 = new Person(12, "Steve Liu"); people.add(person3); Person person4 = new Person(42, "Alice XU"); people.add(person4); return people; } }