Да, со скобочками ты навертел :)
Думаю, имелось в виду что-то такое:
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> listPeople = new ArrayList<>();
listPeople.add(new Person("Mari", "Ke ri", 22));
listPeople.add(new Person("Poti", "Ty Re Mi", 18));
listPeople.add(new Person("Pow", "Keri", 19));
System.out.println(listPeople);
// Можно так
listPeople.sort(new PersonComparator());
// А можно так
listPeople.sort((p1, p2) -> {
int len1 = p1.getSurname().split(" ").length;
int len2 = p2.getSurname().split(" ").length;
if (len1 != len2) {
return Integer.compare(len1, len2);
}
return Integer.compare(p1.getAge(), p2.getAge());
});
System.out.println(listPeople);
}
}
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
int len1 = p1.getSurname().split(" ").length;
int len2 = p2.getSurname().split(" ").length;
if (len1 != len2) {
return Integer.compare(len1, len2);
}
return Integer.compare(p1.getAge(), p2.getAge());
}
}
@AllArgsConstructor
@Getter
@ToString
class Person {
private String name;
private String surname;
private int age;
}
А можно компаратор засадить прямо в класс:
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person2> listPeople2 = new ArrayList<>();
listPeople2.add(new Person2("Mari", "Ke ri", 22));
listPeople2.add(new Person2("Poti", "Ty Re Mi", 18));
listPeople2.add(new Person2("Pow", "Keri", 19));
System.out.println(listPeople2);
// Так
listPeople2.sort((p1,p2)-> p1.compareTo(p2));
// То же самое
listPeople2.sort(Person2::compareTo);
System.out.println(listPeople2);
}
}
@AllArgsConstructor
@Getter
@ToString
class Person2 implements Comparable<Person2> {
private String name;
private String surname;
private int age;
@Override
public int compareTo(Person2 p) {
int len1 = this.surname.split(" ").length;
int len2 = p.getSurname().split(" ").length;
if (len1 != len2) {
return Integer.compare(len1, len2);
}
return Integer.compare(this.age, p.getAge());
}
}