使用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<Hit> hits
- 一个
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
的所有元素,获取其hits字段的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.
谢谢您的帮助!
推荐答案
您可以通过以下方式实现:
You can achieve it by this way :
- 遍历
list
的 - 从
Round
对象更改为其List<Hit> hits
, - 使用
flatMap
从Stream<List<Hits>>
转到Stream<Hits>
- 从
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
所以使用Method reference
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屋!
查看全文