
本文介绍了如何使用 Java Stream API 在 List
原始问题中使用了 ArrayList
例如,可以使用以下 record 来表示数据:
public record Foo(String start, String end, int length) {}这样,就可以使用 List
立即学习“Java免费学习笔记(深入)”;
如果只需要找到一个具有最大 length 值的 Foo 对象,可以使用 Stream.max() 或 Collections.max() 方法。这两个方法都需要一个 Comparator 实例作为参数,用于比较 Foo 对象的 length 属性。
使用 Stream API:
List<Foo> foos = // 初始化列表
Foo max = foos.stream()
.max(Comparator.comparingInt(Foo::length)) // 产生 Optional<Foo>
.orElseThrow();使用 Collections.max():
List<Foo> foos = // 初始化列表 Foo max = Collections.max(foos, Comparator.comparingInt(Foo::length));
Stream.max() 方法返回一个 Optional
如果需要获取所有具有最大 length 值的 Foo 对象集合,可以使用以下两种方法:
方法一:使用 groupingBy()
这种方法首先使用 Collectors.groupingBy() 方法将数据按 length 分组到一个中间 Map 中,然后创建一个流来处理 Map 的条目,并使用 Stream.max() 找到具有最大键(length)的条目。
List<Foo> foos = // 初始化列表
List<Foo> max = foos.stream()
.collect(Collectors.groupingBy(Foo::length)) // Map<Integer, List<Foo>>
.entrySet().stream() // Stream<Map.Entry<Integer, List<Foo>>>
.max(Map.Entry.comparingByKey()) // Optional<Map.Entry<Integer, Foo>>
.map(Map.Entry::getValue) // Optional<List<Foo>>
.orElse(Collections.emptyList());方法二:使用三参数的 collect()
这种方法使用 Stream.collect() 方法的三参数版本,将流元素累积到一个列表中,该列表将作为流执行的结果返回。
List<Foo> foos = // 初始化列表
List<Foo> max = foos.stream()
.collect(
ArrayList::new,
(List<Foo> l, Foo f) -> {
if (!l.isEmpty() && l.get(0).length() < f.length()) l.clear();
if (l.isEmpty() || l.get(0).length() == f.length()) l.add(f);
},
(l, r) -> {
if (l.get(0).length() < r.get(0).length()) l.clear();
if (l.isEmpty() || l.get(0).length() == r.get(0).length()) l.addAll(r);
}
);这种方法避免了创建中间 Map 和第二个流来处理 Map 的条目,效率更高。
本文介绍了如何使用 Java Stream API 在 List
注意事项:
通过使用 Java Stream API,可以更简洁、更高效地处理集合数据,提高代码的可读性和可维护性。
以上就是使用 Java Stream API 查找 List 中具有最大值的 Map的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号