I would like to get the max value out of a list using java 8 stream methods.
The structure is the following:
Use flatMap
:
int maxPrize = arrRound.stream() // Stream<Round>
.flatMap(r -> r.getHits().stream()) // Stream<Hit>
.mapToInt(Hit::getPrizeAmount) // IntStream
.max()
.orElse(0);
using reduce
int max1 = arrRound.stream()
.flatMap(r -> r.getHits().stream())
.mapToInt(h -> h.getPrizeAmount())
.reduce(Math::max) //returns OptionalInt
.orElse(Integer.MIN_VALUE);
or
int max2 = arrRound.stream()
.flatMap(r -> r.getHits().stream())
.mapToInt(h -> h.getPrizeAmount())
.reduce(Integer.MIN_VALUE, Math::max);
You can achieve it by this way :
Round
of the list
Round
object to its List<Hit> hits
,flatMap
to go from Stream<List<Hits>>
to Stream<Hits>
Hits
to its prizeAmount
fieldmax
if exists-1
So a solution using 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
With class lambda
and map + flatMap
in one :
int maxPrize = arrRoundarrRound.stream()
.flatMap(round -> round.getHits().stream())
.mapToInt(hits -> hits.getPrizeAmount())
.max()
.orElse(-1);
using Comparator
:
int max2 = arrRound.stream()
.flatMap(round -> round.getHits().stream())
.max(Comparator.comparing(Hits::getPrizeAmount))
.map(Hits::getPrizeAmount)
.orElse(-1);
Because forEach
is a terminal operation.
And after you call the forEach
on a stream the stream terminates and can't be used again.