java - java android中的ArrayList groupby基于相同的属性,没有java 8流和lambda
问题描述
我的对象如下所示
class Item{
String color;
int price;
int size;
}
现在我的数组列表包含 item 类型的对象
我想创建具有相同价格的项目的子列表。
想要将项目分组到具有相同颜色的子列表中。
想要创建具有相同大小的项目的子列表。
因为我在 android 中实现这个并且想要支持所有 android 版本我不能使用 Lambda 和 Stream
我想使用 apache 的 CollectionUtils 或 google 的 Guava,但不知道如何帮助?
解决方案
使用 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}]
推荐阅读
- excel - VBA QueryTable.Refresh
- xamarin - 在 Xamarin.Forms 中使用 ToptabbedPage 时出现意外的白色按钮
- flutter - 在颤振应用程序的发布模式下,文本变灰
- python - csv 文件转换成表格 - Python 编程
- php - 如何从这个数组制作一个表格?
- xamarin - Xamarin 按钮未启用
- javascript - 单击时更改元素索引(两侧)
- javascript - 为什么这个数组在看起来正确的范围内被记录为未定义?
- python - 给定 3 个非负整数 n、m 和 a,找到满足 (x*a) % n = m % n 的最小 x 的最快方法是什么?
- java - 如何检查 2d 点是否在 Java 中的 2D 多边形内?