如何在 Java 8 中使用流从整数中找到最大值? [英] How to find maximum value from a Integer using stream in Java 8?

查看:27
本文介绍了如何在 Java 8 中使用流从整数中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Integer list 列表,从 list.stream() 我想要最大值.

I have a list of Integer list and from the list.stream() I want the maximum value.

最简单的方法是什么?我需要比较器吗?

What is the simplest way? Do I need comparator?

推荐答案

您可以将流转换为 IntStream:

OptionalInt max = list.stream().mapToInt(Integer::intValue).max();

或者指定自然顺序比较器:

Or specify the natural order comparator:

Optional<Integer> max = list.stream().max(Comparator.naturalOrder());

或者使用reduce操作:

Or use reduce operation:

Optional<Integer> max = list.stream().reduce(Integer::max);

或者使用收集器:

Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));

或使用 IntSummaryStatistics:

Or use IntSummaryStatistics:

int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();

这篇关于如何在 Java 8 中使用流从整数中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆