Using Java 8 stream methods to get a max value

前端 未结 5 1237
暖寄归人
暖寄归人 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:39

    Use flatMap:

    int maxPrize = arrRound.stream() // Stream<Round>
                           .flatMap(r -> r.getHits().stream()) // Stream<Hit>
                           .mapToInt(Hit::getPrizeAmount) // IntStream
                           .max()
                           .orElse(0);
    
    0 讨论(0)
  • 2021-01-22 00:42

    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);
    
    0 讨论(0)
  • 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<Hit> hits,
    • use flatMap to go from Stream<List<Hits>> to Stream<Hits>
    • 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<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); 
    
    0 讨论(0)
  • 2021-01-22 00:53

    using Comparator:

    int max2 = arrRound.stream()
                .flatMap(round -> round.getHits().stream())
                .max(Comparator.comparing(Hits::getPrizeAmount))
                .map(Hits::getPrizeAmount)
                .orElse(-1);
    
    0 讨论(0)
  • 2021-01-22 01:01

    Because forEach is a terminal operation. And after you call the forEach on a stream the stream terminates and can't be used again.

    0 讨论(0)
提交回复
热议问题