2

I am trying to sort a list based on sort key and sort order I receive from an API. For example, I have a list with sortkey and sortorder and based on that I need to sort.

List<SortList> sortlist;

I have a list of an object :

List<Employee> employee;

I am able to sort using

Collections.sort(sourceList, Comparator
                .comparing(Employee::getAge).reversed()
                .thenComparing(Employee::getCount));

But i need to check the sortfeild on a condition and based on that only the field is considered for sorting.

ex:

if(sortkey = "name") sortbythatkey from sortlist by the sort order

if (sortkey = "place") sortbythat key from sortlist by the sort order

So here if sortlist has both name and place then it should sort by both key and order

Any idea how could i achieve this?

Sort List contains:

{
    "sortKey":"name",
    "sortOrder":"ASC"

},
{
    "sortKey":"place",
    "sortOrder":"DESC"

}

Requirement is to chain them together like ORDER BY in SQL

4
  • How do you need it to behave if two elements have different sortkeys?
    – Marv
    Jul 25, 2019 at 7:27
  • @Marv : Actually the sortkeys and order will be provided externally. so should chain the sorting based on that sortkeys and sort order Jul 25, 2019 at 7:37
  • Can you give an example of what the sortlist might contain?
    – Sweeper
    Jul 25, 2019 at 7:47
  • @Sweeper Added...... Jul 25, 2019 at 9:47

2 Answers 2

1

Assuming that sortlist is a list of SortCriteria, which is a class like this:

class SortCritera {
    private String key;
    private String order;

    public String getKey() {
        return key;
    }

    public String getOrder() {
        return order;
    }

    // constructors, setters...
}

You first need a HashMap<String, Comparator<Employee>> to store all the corresponding comparators for each possible key:

HashMap<String, Comparator<Employee>> comparators = new HashMap<>();
comparators.put("name", Comparator.comparing(Employee::getName));
comparators.put("age", Comparator.comparing(Employee::getAge));
// ...

Then you can loop through the sortlist and keep calling thenComparing:

Comparator<Employee> comparator = comparators.get(sortlist.get(0).getKey());
if (sortlist.get(0).getOrder().equals("DESC")) {
    comparator = comparator.reversed();
}
for(int i = 1 ; i < sortlist.size() ; i++) {
    if (sortlist.get(i).getOrder().equals("DESC")) {
        comparator = comparator.thenComparing(comparators.get(sortlist.get(i).getKey()).reversed());
    } else {
        comparator = comparator.thenComparing(comparators.get(sortlist.get(i).getKey()));
    }
}
// now you can sort with "comparator".

As Holger has suggested, you can use the Stream API to do this as well:

sortlist.stream().map(sc -> {
    Comparator<Employee> c = comparators.get(sc.getKey()); 
    return sc.getOrder().equals("DESC")? c.reversed(): c; 
}).reduce(Comparator::thenComparing)
.ifPresent(x -> Collections.sort(originalList, x));
23
  • Why 1st get(0) case is given outside the for loop? and it is not checking for ASC case right? Jul 25, 2019 at 10:20
  • @KarthikCherukunnumal The first case is special because you need to call comparing instead of thenComparing. I am assuming that if it is not descending, it is ascending.
    – Sweeper
    Jul 25, 2019 at 10:21
  • ok, but for second case we are thenComparing with Comparator.comparing(Employee::getName) right? will that work? Jul 25, 2019 at 10:26
  • 1
    Lots of code duplication inside the loop body. How about another local variable? Comparator<Employee> next = comparators.get(sortlist.get(i).getKey()); if(sortlist.get(i).getOrder().equals("DESC")) { next = comparator.reversed(); } comparator = comparator.thenComparing(next); Or you use the Stream API with Reduction: sortlist.stream() .map(sc -> { Comparator<Employee> c = comparators.get(sc.getKey()); return sc.getOrder().equals("DESC")? c.reversed(): c; }) .reduce(Comparator::thenComparing) .ifPresent(theList::sort);
    – Holger
    Jul 25, 2019 at 11:13
  • 1
    Instead of x -> Collections.sort(originalList, x) you can also use x -> originalList.sort(x), which is equivalent to originalList::sort
    – Holger
    Jul 25, 2019 at 11:53
1

You can create a method which when passed the sort key, you provide the proper Comparator:

public Comparator<Employee> getComparator(String sortKey) {
    if("name".equals(sortKey)) {
        return Comparator.comparing(Employee::getName);
    } else if ("place".equals(sortKey) {
        return Comparator.comparing(Employee::getPlace);
    } else {
        throw new IllegalArgumentException();
    }
}

To call it it would simply be:

Collections.sort(sourceList, getComparator(sortKey).reversed()
                .thenComparing(Employee::getCount));

While you could also write your own, I find it is better to delegate the "standard" parts and simply write the part that differs from this.

If you find yourself having many such sort keys, then a more suitable means to do this would be to use a map:

private static final Map<String, Comparator<Employee>> COMPARE_MAP = new HashMap<>() {{
    put.("name", Comparator.comparing(Employee::getName));
    put.("place", Comparator.comparing(Employee::getPlace));
}});

public Comparator<Employee> getComparator(String sortKey) {
    if(COMPARE_MAP.containsKey(sortKey)) {
        return COMPARE_MAP.get(sortKey);
    } else {
        throw new IllegalArgumentException();
    }
}

Reflection is also an option, but I would be cautious to use reflection unless it becomes impractical to do otherwise. In that case, you could create your own annotation to determine which fields of class Employee can be used for sorting.

8
  • Here how could I determine the sort order, sort order from request may contain DESC and ASC, so how to sort based on that by this? also will it work like chaining them together? Jul 25, 2019 at 7:39
  • 1
    It's much cleaner to use a Map for this sort of thing. Jul 25, 2019 at 7:41
  • @chrylis True, in fact if I had to add just one more here, I would most certainly use a map. I'll adjust my answer accordingly.
    – Neil
    Jul 25, 2019 at 7:49
  • @Neil : here how could i add sortOrder, as i also check need to check the sortOrder and sort accordingly Jul 25, 2019 at 8:02
  • 1
    Using a Map is a clean approach, creating a subclass of HashMap, just for the sake of saving a few characters in source code, is not. Besides, put.( is not even valid syntax.
    – Holger
    Jul 25, 2019 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.