首页 > 解决方案 > java android中的ArrayList groupby基于相同的属性,没有java 8流和lambda

问题描述

我的对象如下所示

 class Item{
    String color;
    int price;
    int size;
}

现在我的数组列表包含 item 类型的对象

我想创建具有相同价格的项目的子列表。

想要将项目分组到具有相同颜色的子列表中。

想要创建具有相同大小的项目的子列表。

因为我在 android 中实现这个并且想要支持所有 android 版本我不能使用 Lambda 和 Stream

我想使用 apache 的 CollectionUtils 或 google 的 Guava,但不知道如何帮助?

标签: javaandroidarraylistcollectionsguava

解决方案


使用 Guava,您可以Multimap使用Multimaps#index(Iterable, Function).

请注意,没有 lambdas 函数非常麻烦。查看获取价格的函数的定义(可以内联):

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}]

推荐阅读