Let's study Java 8 method references with you this time.
First of all, let's make an age sword method by the method before Java 8.
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//Anonymous class
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
}
Implementation results: [Person (name = Mary, age = 23), Person (name = Jill, age = 24), Person (name = Jack, age = 25), Person (name = Lily, age = 27), Person (name = Dock, age = 34)]
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//Lambda expression
Collections.sort(personList,(p1,p2) -> p1.getAge() - p2.getAge());
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
}
Implementation results: [Person (name = Mary, age = 23), Person (name = Jill, age = 24), Person (name = Jack, age = 25), Person (name = Lily, age = 27), Person (name = Dock, age = 34)]
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;
public class App {
public static void main( String[] args ) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack",25));
personList.add(new Person("Mary",23));
personList.add(new Person("Jill",24));
personList.add(new Person("Dock",34));
personList.add(new Person("Lily",27));
//static method reference
Collections.sort(personList, Person::CompareAge);
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
public static int CompareAge(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
}
Recommended Posts