使用 Guava,您可以创建 Multimap,其中键是您想要的属性(例如价格),值是使用 Multimaps#index(Iterable, Function) 的每个组的项目。
请注意,如果没有 lambda,函数会非常麻烦。查看获取价格的函数定义(可以内联):
private static final Function<Item, Integer> TO_PRICE =
new Function<Item, Integer>() {
@Override
public Integer apply(Item item) {
return item.price;
}
};
创建您的分组多图:
ImmutableListMultimap<Integer, Item> byPrice = Multimaps.index(items, TO_PRICE);
样本数据:
ImmutableList<Item> items = ImmutableList.of(
new Item("red", 10, 1),
new Item("yellow", 10, 1),
new Item("green", 10, 2),
new Item("green", 42, 4),
new Item("black", 4, 4)
);
用法:
System.out.println(byPrice);
// {10=[Item{color=yellow, price=10, size=1}, Item{color=green, price=10, size=2}], 42=[Item{color=green, price=42, size=4}], 4=[Item{color=black, price=4, size=4}]}
System.out.println(byPrice.values());
// [Item{color=yellow, price=10, size=1}, Item{color=green, price=10, size=2}, Item{color=green, price=42, size=4}, Item{color=black, price=4, size=4}]
System.out.println(byPrice.get(10));
//[Item{color=yellow, price=10, size=1}, Item{color=green, price=10, size=2}]