【问题标题】:ArrayList groupby in java android based on same attributes without java 8 stream and lambdajava android中的ArrayList groupby基于相同的属性,没有java 8流和lambda
【发布时间】:2018-12-01 05:32:04
【问题描述】:

我的对象如下所示

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

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

我想创建价格相同的商品的子列表。

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

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

由于我在 android 中实现此功能并希望支持所有 android 版本,因此我无法使用 Lambda 和 Stream

我想使用 apache 的 CollectionUtils 或 google 的 Guava,但不知道怎么做?

【问题讨论】:

  • 看看this
  • 它只是用于 String 我正在寻找基于属性的对象

标签: java android arraylist collections guava


【解决方案1】:

使用 Guava,您可以创建 Multimap,其中键是您想要的属性(例如价格),值是使用 Multimaps#index(Iterable, Function) 的每个组的项目。

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

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

【讨论】:

  • 我有 List 项如何将它们转换为 ImmutableListMultimap
  • @apk ImmutableListMultimap&lt;Integer, Item&gt; byPrice = Multimaps.index(items, TO_PRICE); 如答案中所述,其中TO_PRICE 是您定义的Function(内联或常量,如上所述)。
  • 哦,谢谢,我想我必须先创建 ImmutableList
  • Multimaps#index 接受任何Iterable,因此任何ListSet 甚至Collection 都可以。
  • 嘿,抱歉,还有一个查询如何按索引访问 ImmutableListMultimap
【解决方案2】:

试试这个

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.

【讨论】:

  • 寻找更优化的方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多