List<Object> 根据 编码分组,取最大值,转换为 <String,Date>
时间: 2023-11-11 09:24:49 浏览: 86
同样可以使用 Java 8 的 Stream API 来实现这个需求。具体实现步骤如下:
- 使用 Stream 的
collect()
方法将 List 转换为 Map,其中键为编码,值为包含编码和数值的对象。 - 使用 Stream 的
map()
方法将 Map 中的对象转换为包含编码和数值的字符串。 - 使用 Stream 的
groupingBy()
方法将字符串按照编码分组。 - 使用 Stream 的
max()
方法获取每组中数值最大的对象。 - 使用 Stream 的
map()
方法将每组中的对象转换为包含编码和数值的键值对。
代码如下:
List<Object> list = ...; // 给定的 List
Map<String, Object> map = list.stream()
.collect(Collectors.toMap(
obj -> ((YourObject) obj).getEncoding(), // 键为编码
obj -> obj, // 值为包含编码和数值的对象
(a, b) -> a.getValue() > b.getValue() ? a : b // 合并时取数值最大的对象
));
Map<String, Integer> result = map.entrySet().stream()
.map(entry -> entry.getValue().getEncoding() + "," + entry.getValue().getValue()) // 将对象转换为字符串
.collect(Collectors.groupingBy(
str -> str.split(",")[0], // 按照编码分组
Collectors.maxBy(Comparator.comparing(str -> Integer.parseInt(str.split(",")[1]))))) // 获取每组中数值最大的字符串
.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey, // 键为编码
entry -> Integer.parseInt(entry.getValue().get().split(",")[1]))); // 值为数值
这样就可以将 List
相关推荐


















