Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList groupby in java android based on same attributes without java 8 stream and lambda

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?

like image 451
amodkanthe Avatar asked Mar 05 '26 20:03

amodkanthe


1 Answers

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}]
like image 169
Xaerxess Avatar answered Mar 08 '26 09:03

Xaerxess