I have custom Comparator ChainedComparator
and and it has multiple comparator in it, which will be passed at runtime.
class ChainedComparator implements Comparator<Person> {
private List<Comparator<Person>> comparatorList;
public int compare(Person o1, Person o2) {
for (Comparator<Person> comparator : comparatorList) {
int result = comparator.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
@SafeVarargs
public ChainedComparator(Comparator<Person>... comparators) {
this.comparatorList = Arrays.asList(comparators);
}
}
now i want to create comparator at run time from the field name age , rather than hardcoding like below
Comparator<Person> ageComparator = Comparator.comparing(Person::getAge);
Comparator<Person> lastNameComparator = Comparator.comparing(Person::getLastName);
Comparator<Person> ageComparator = Comparator.comparing(Person::getAge);
personList.stream().sorted(new ChainedComparator(firstNameComparator,ageComparator))
any advice please
class Person {
Person(){}
String firstName;
String lastName;
int age;
String country;
public Person( String firstName, String lastName, int age,String country) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.country = country;
}
// getters and setters
}
Aucun commentaire:
Enregistrer un commentaire