Using Guava, you can create Multimap
in which keys are your desired property (ex. price) and values are items for each group by using Multimaps#index(Iterable, Function)
.
Note that without lambdas functions are very cumbersome. See a definition of a function for getting price (could be inlined):
private static final Function<Item, Integer> TO_PRICE =
new Function<Item, Integer>() {
@Override
public Integer apply(Item item) {
return item.price;
}
};
Create your grouped multimap:
ImmutableListMultimap<Integer, Item> byPrice = Multimaps.index(items, TO_PRICE);
Sample data:
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)
);
Usage:
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}]