My object looks something like below
class Item{
String color;
int price;
int size;
}
Now my arraylist contains objects of type item
I want to create sublist of items having same price.
Want to group items into sublist with same color.
Want to create sublist of items with same size.
Since I am implementing this in android and want to support all android version I can't use Lambda and Stream
I want to use CollectionUtils by apache or Guava by google but don't know how to do it any help?
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With