|
| 1 | +package lambda; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.Comparator; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class LEComparator { |
| 9 | + public static void main(String[] args) { |
| 10 | + |
| 11 | + List<Person> personList = new ArrayList<>(); |
| 12 | + personList.add(new Person("John", 20)); |
| 13 | + personList.add(new Person("Mary", 25)); |
| 14 | + personList.add(new Person("Peter", 30)); |
| 15 | + personList.add(new Person("Anna", 28)); |
| 16 | + personList.add(new Person("Paul", 35)); |
| 17 | + |
| 18 | + //without lambda expression |
| 19 | + //sort by age |
| 20 | + Comparator<Person> comparator =new Comparator<Person>() { |
| 21 | + @Override |
| 22 | + public int compare(Person o1, Person o2) { |
| 23 | + return o1.getAge() - o2.getAge(); |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + Collections.sort(personList, comparator); |
| 28 | + System.out.println("Sort Person List by age in ascending order:"); |
| 29 | + for (Person person : personList) { |
| 30 | + System.out.println(person.getName() + " " + person.getAge()); |
| 31 | + } |
| 32 | + |
| 33 | + //with lambda expression |
| 34 | + Collections.sort(personList, (o1, o2) -> o1.getAge() - o2.getAge()); |
| 35 | + System.out.println("Sort Person List by age in ascending order:"); |
| 36 | + personList.forEach( |
| 37 | + (person -> System.out.println(person.getName() + " " + person.getAge())) |
| 38 | + ); |
| 39 | + |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +class Person{ |
| 44 | + String name; |
| 45 | + int age; |
| 46 | + |
| 47 | + public Person(String name, int age) { |
| 48 | + this.name = name; |
| 49 | + this.age = age; |
| 50 | + } |
| 51 | + |
| 52 | + public String getName() { |
| 53 | + return name; |
| 54 | + } |
| 55 | + |
| 56 | + public void setName(String name) { |
| 57 | + this.name = name; |
| 58 | + } |
| 59 | + |
| 60 | + public int getAge() { |
| 61 | + return age; |
| 62 | + } |
| 63 | + |
| 64 | + public void setAge(int age) { |
| 65 | + this.age = age; |
| 66 | + } |
| 67 | +} |
0 commit comments