Using Java 8 stream methods to get a max value

前端 未结 5 1248
暖寄归人
暖寄归人 2021-01-22 00:00

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
5条回答
  •  醉话见心
    2021-01-22 00:47

    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); 
    

提交回复
热议问题