Streams Sorting by runtime parameter

Viewed 304

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
}
1 Answers

The simplest, static way to do this may be to just maintain a field name -> Comparator map, like this:

private static Map<String, Comparator<Person>> comparatorMap = Map.of(
        "age", Comparator.comparing(Person::getAge),
        "firstName", Comparator.comparing(Person::getFirstName),
        "lastName", Comparator.comparing(Person::getLastName),
        "country", Comparator.comparing(Person::getCountry)
    );

Which, given a field list like

List<String> sortFields = Arrays.asList("age", "firstName", "lastName");

can be used to produce a composed comparator:

Optional<Comparator<Person>> chainedComparator = 
    sortFields.stream().map(comparatorMap::get).reduce(Comparator::thenComparing);

personList.stream().sorted(chainedComparator.get());

You can also notice that I used Comparator's own thenComparing to compose comparators (instead of implementing it yourself).


Here's an example implementation using reflection to dynamically select the fields to sort by

Before it's used, note: * It assumes that fields are of Comparable types (if you pass the name of a field whose type is not comparable, a class cast exception will be raised) * I'm creating a comparator each time, you may want to store them against the field name, if that's necessary

private static Comparator<Person> personFieldComparator(String field) {
    return (person1, person2) -> readPersonField(person1, field)
            .compareTo(readPersonField(person2, field));
}

private static Comparable<Object> readPersonField(Person person, String field) {

    try {
        Field f = Person.class.getDeclaredField(field);
        f.setAccessible(true);

        return (Comparable<Object>) f.get(person);
    } catch (IllegalAccessException | IllegalArgumentException
             | NoSuchFieldException e) {
        throw new RuntimeException(e); //proper handling needed
    }
}

And with that, you can change the initial implementation to something like:

Optional<Comparator<Person>> chainedComparator = sortFields.stream()
        .map(Main::personFieldComparator) //Main -> Your class name
        .reduce(Comparator::thenComparing);
personList.stream().sorted(chainedComparator.orElseThrow())...;

You may choose to extend this by using generics to make it not Person-specific

Related