I am trying to build custom comparison logic using Comparator.comparing() introduced in Java 8.
Requirement is: code should work if a new field is introduced in Person class. It should take new field into comparison logic.
It means comparison logic should be like this : id --> name --> new field1 --> new field2
See pseudo code below :
package test;
import java.lang.reflect.Field;
import java.util.Comparator;
public class Test6 {
public static void main (String args []) {
Field[] declaredFields = Person.class.getDeclaredFields();
Comparator<Person> comparator = Comparator.comparing((Person x)-> x.getId());
for (int i=1; i<declaredFields.length ; i++) {
comparator = comparator.thenComparing(field[i]); // what code should I place over here, to make it work for field obtained above.
}
List<Person> persons = new ArrayList<>();
persons.stream().sorted(comparator).collect(Collectors.toList());
}
}
class Person{
int id ;
String name;
// if we add new field , then this field should also be included in comparison logic
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}