Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambdaj and Multiple Sort Conditions in Java

I love lambdaj and use it a lot, but I can't seem to figure out if it is possible to sort a list using multiple sort conditions.

Here is an example using Google Collections. Can the same thing be done in lambdaj?

Sorted first by color then by name:

Function<Fruit, Color> getColorFunction = new Function<Fruit, Color>() {
public Color apply(Fruit from) {
    return from.getColor();
}
};

Function<Fruit, String> getNameFunction = new Function<Fruit, String>() {
public String apply(Fruit from) {
    return from.getName();
}
};

Ordering<Fruit> colorOrdering = Ordering.natural().onResultOf(getColorFunction);
Ordering<Fruit> nameOrdering = Ordering.natural().onResultOf(getNameFunction);

Ordering<Fruit> colorAndNameOrdering = colorOrdering.compound(nameOrdering);

ImmutableSortedSet<Fruit> sortedFruits = ImmutableSortedSet.orderedBy(
    colorAndNameOrdering).addAll(fruits).build();
like image 317
gobbler Avatar asked May 07 '26 18:05

gobbler


1 Answers

Examples of doing that aren't provided on official Lambdaj page, but under hood each time when you are calling sort Lambdaj creates comparator for given argument. Below is an example how to sort by multiple attributes.

Sorting:

public static void main(String... args) {
    final Comparator byName = new ArgumentComparator(on(Fruit.class).getName());
    final Comparator byColor = new ArgumentComparator(on(Fruit.class).getColor());
    final Comparator orderBy = ComparatorUtils.chainedComparator(byName, byColor);

    final List<Fruit> unsorted = Arrays.asList(...);

    final List<Fruit> sorted = sort(unsorted, on(Fruit.class), orderBy);

    System.out.println(sorted);
}

Downside:

There's one non-lambdaj 3rd party method usage. ComparatorUtils.chainedComparator - it's from apache commons collections. If you don't have this as a dependency in your project you can write your own. it just iterates thru all comparators untill non zero returned.

like image 194
Petro Semeniuk Avatar answered May 11 '26 07:05

Petro Semeniuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!