Reputation: 21
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();
Upvotes: 2
Views: 3769
Reputation: 7038
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.
Upvotes: 12