使用 Java 8 流方法获取最大值 [英] Using Java 8 stream methods to get a max value
本文介绍了使用 Java 8 流方法获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 java 8 流方法从列表中获取最大值.
I would like to get the max value out of a list using java 8 stream methods.
结构如下:
- 我读取了一个 csv 文件并将每一行的数据存储在一个
Round
类型的单独对象中. - 所有这些
Round
对象都存储在一个名为arrRound
的 - 所有
Round
对象都有一个字段:List
命中 - a
Hit
包含 2 个字段:int numberOfGames
和int PrizeAmount
ArrayList
中- I read a csv file and store the data of every line in a separate object of type
Round
. - all these
Round
objects are stored in anArrayList
calledarrRound
- all
Round
objects have a field:List<Hit> hits
- a
Hit
consists of 2 fields:int numberOfGames
andint prizeAmount
public class Round{
private List<Hits> hits;
}
public class Hits{
private int numberOfGames;
private int prizeAmount;
}
<小时>
我想做的是遍历 arrRound
的所有元素,获取它们的命中字段的 getPrizeAmount()
方法并从中获取最大值.我从以下开始,但似乎无法做到:
What I would like to do is to iterate over all elements of arrRound
, get their hits field's getPrizeAmount()
method and get the max out of it.
I started as the following but can't seem to do it:
public class Main(){
public void main(String[]args){
List<Round> arrRound = getRoundFromCSV();
int maxPrize = arrRound.stream()
.forEach(round -> {
round.getHits()
.forEach(hit -> hit.getPrizeAmount());
});
}
}
并且我无法在语句的末尾调用 max().
and I am not able to call max() on the end of the statement.
提前感谢您的帮助!
推荐答案
你可以这样实现:
- 遍历
list
的 - 从
Round
对象更改为它的List
,点击次数 - 使用
flatMap
从Stream
到- >
Stream
- 从
Hits
更改为它的prizeAmount
字段 - 获取
max
(如果存在) - 如果没有最大值(如列表为空或其他)返回
-1
Round
- iterate over the
Round
of thelist
- change from
Round
object to itsList<Hit> hits
, - use
flatMap
to go fromStream<List<Hits>>
toStream<Hits>
- change from
Hits
to itsprizeAmount
field - get the
max
if exists - if no max (like if list empty or else) return
-1
所以一个使用方法参考
int maxPrize = arrRoundarrRound.stream() // Stream<Round>
.map(Round::getHits) // Stream<List<Hits>>
.flatMap(List::stream) // Stream<Hits>
.mapToInt(Hit::getPrizeAmount) // IntStream
.max() // OptionalInt
.orElse(-1); // int
lambda
和 map + flatMap
合二为一:
int maxPrize = arrRoundarrRound.stream()
.flatMap(round -> round.getHits().stream())
.mapToInt(hits -> hits.getPrizeAmount())
.max()
.orElse(-1);
这篇关于使用 Java 8 流方法获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文