Sort – sort a table across multiple comparator items
I need to use multiple comparator objects in Java 8 to sort the list of item objects
The application creates a comparator for each user action It stores comparator objects in ArrayList You can sort one comparator item, but now we need a way to sort multiple comarator items at the same time
I use this line of code to sort the list:
tbl.getItems().stream().sorted(groupingComparator);
The variable groupingcomparator comes from the comparator < item > type
Now I need to sort multiple fields stored in it
ArrayList<Comparator<Item>>
Is this possible in Java 8? How can I achieve it?
Solution
You can link multiple comparators together using thencomparing (comparator) method provided by the comparator interface See the following example to create such a chained comparator from a list using a stream
The domain class we want to use for sorting:
public static class Order { String customer; String item; public Order(String customer,String item) { this.customer = customer; this.item = item; } public String toString() { return "Customer: " + customer + " Item: " + item; } }
Example code:
public static void main(String... args) throws Throwable { List<Order> orders = new ArrayList<>(); orders.add(new Order("A","Item 1")); orders.add(new Order("B","Item 3")); orders.add(new Order("A","Item 2")); orders.add(new Order("B","Item 1")); List<Comparator<Order>> comparators = Arrays.asList((o1,o2) -> o1.customer.compareTo(o2.customer),// comparator for customer names (o1,o2) -> o1.item.compareTo(o2.item)); // comparator for item names Comparator<Order> comp = comparators.stream() .reduce(Comparator::thenComparing) // use a default comparator if the comparator list was empty .orElse(Comparator.comparing(Object::toString)); orders.stream().sorted(comp).forEach((order) -> System.out.println(order)); }
This code snippet will print the order first sorted by item name by customer