1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.util.Comparator; public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public static void sort(List<Person> l, String title, Comparator<Person> comp) { Collections.sort(l, comp); System.out.println(title); for(Person p: l) { System.out.println(p.name + " " + p.age); } } public static void main(String []args){ ArrayList<Person> l = new ArrayList<>(); l.add(new Person("A", 30)); l.add(new Person("B", 29)); l.add(new Person("C", 28)); l.add(new Person("D", 27)); sort(l, "Sorting by name", (p1, p2) -> p1.name.compareTo(p2.name)); sort(l, "Sorting by age", (p1, p2) -> (p1.age - p2.age)); } } |
Saturday, July 27, 2019
Sort java list, lambda comparators
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment