小编gob*_*ler的帖子

lambdaj和Java中的多个排序条件

我喜欢lambdaj并且经常使用它,但我似乎无法弄清楚是否可以使用多种排序条件对列表进行排序.

以下是使用Google Collections的示例.可以在lambdaj中完成同样的事情吗?

首先按颜色排序,然后按名称排序:

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();
Run Code Online (Sandbox Code Playgroud)

java sorting collections lambdaj

2
推荐指数
1
解决办法
3632
查看次数

标签 统计

collections ×1

java ×1

lambdaj ×1

sorting ×1