Lassen Sie uns diesmal die Java 8-Methodenreferenz mit Ihnen studieren.
Lassen Sie uns zunächst eine Methode für das Altersschwert nach der Methode vor Java 8 erstellen.
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));
//Anonyme Klasse
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;
}
Implementierungsergebnis: [Person (Name = Mary, Alter = 23), Person (Name = Jill, Alter = 24), Person (Name = Jack, Alter = 25), Person (Name = Lily, Alter = 27), Person (Name = Dock, Alter = 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-Formel
Collections.sort(personList,(p1,p2) -> p1.getAge() - p2.getAge());
System.out.println(personList);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private int age;
}
Implementierungsergebnis: [Person (Name = Mary, Alter = 23), Person (Name = Jill, Alter = 24), Person (Name = Jack, Alter = 25), Person (Name = Lily, Alter = 27), Person (Name = Dock, Alter = 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));
//statische Methodenreferenz
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