java8 stream 最大值,使用Java 8流方法获取最大值

I would like to get the max value out of a list using java 8 stream methods.

The structure is the following:

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 an ArrayList called arrRound

all Round objects have a field: List hits

a Hit consists of 2 fields: int numberOfGames and int prizeAmount

public class Round{

private List hits;

}

public class Hits{

private int numberOfGames;

private int prizeAmount;

}

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 arrRound = getRoundFromCSV();

int maxPrize = arrRound.stream()

.forEach(round -> {

round.getHits()

.forEach(hit -> hit.getPrizeAmount());

});

}

}

and I am not able to call max() on the end of the statement.

Thank you for your help in advance!

解决方案

You can achieve it by this way :

iterate over the Round of the list

change from Round object to its List hits,

use flatMap to go from Stream> to Stream

change from Hits to its prizeAmount field

get the max if exists

if no max (like if list empty or else) return -1

So a solution using Method reference

int maxPrize = arrRoundarrRound.stream() // Stream

.map(Round::getHits) // Stream>

.flatMap(List::stream) // Stream

.mapToInt(Hit::getPrizeAmount) // IntStream

.max() // OptionalInt

.orElse(-1); // int

With class lambda and map + flatMap in one :

int maxPrize = arrRoundarrRound.stream()

.flatMap(round -> round.getHits().stream())

.mapToInt(hits -> hits.getPrizeAmount())

.max()

.orElse(-1);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值