java - 基于不同和第二个谓词的过滤器列表
问题描述
我的对象如下所示
Store {
String shopId;
long distance;
}
我有一个商店列表。
List<Store> storesList = Arrays.asList(
new Store (1, 1),
new Store (1, 5),
new Store (2, 2),
new Store (1, 1), // this is duplicate
new Store (1, 2),
new Store (1, 1), // this is duplicate
new Store (3, 7)
new Store (3, 5)
);
输出
Store {shopId=1, distance=1} // its fine to have any one among 3 duplicates
Store {shopId=2, distance=2}
Store {shopId=3, distance=5}
我可以调用我自己的 distint 方法,如下所示
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
并像这样过滤它
List<Store> stores= storesList .stream()
.filter(distinctByKey(pr -> Arrays.asList(pr.getShopId())))
.collect(toList());
但是如何通过更小的距离同时过滤它呢?
解决方案
storesList.stream()
.collect(Collectors.toMap(
Store::getShopId,
Function.identity(),
BinaryOperator.minBy(Comparator.comparingLong(Store::getDistance))
))
.values()
.forEach(System.out::println);
您可以合并这些相同Store
的 s (by storeId
),您会说在合并时您将distance
在两个 Store 之间取最小的。
推荐阅读
- html - 通过电子邮件发送 Excel 表格时保留单元格注释(使用 RangeToHTML)
- android - React Native FlatList Grid 自定义视图
- java - HTTP 状态 404 – 应用程序运行时未找到
- prometheus - 如何在 Prometheus 中仅远程写入所有抓取指标的子集?
- python - 在 Python 中在其他元素之上创建一个 Tkinter 元素
- google-app-engine - 在 CloudSQL 上恢复已删除的数据库
- python - Python制作没有numpy,pandas的csv特定行的表格图表
- python - 有没有办法将 NaN 的元素设置为 0?
- azure-functions - 结构图和新的 Azure Function DI
- java - 避免数据库节流的动态速率限制器