3

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?

amodkanthe
  • 4,345
  • 6
  • 36
  • 77

2 Answers2

3

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}]
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
2

Try this

Map<String, List<Item>> map = new HashMap<>();
for (Item item : items) {
   List<Item> list;
   if (map.containsKey(item.getColor())) {
      list = map.get(item.getColor());
   } else {
      list = new ArrayList<>();
   }
   list.add(item);
   map.put(item.getColor(), list);
}
map.values(); // this will give Collection of values.
kTest
  • 367
  • 1
  • 11