使用 Java 8 流方法获取最大值 [英] Using Java 8 stream methods to get a max value

查看:85
本文介绍了使用 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
  • ArrayList
  • 所有 Round 对象都有一个字段:List命中
  • a Hit 包含 2 个字段:int numberOfGamesint PrizeAmount
  • 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<Hit> hits
  • a Hit consists of 2 fields: int numberOfGames and int prizeAmount
public class Round{
    private List<Hits> hits; 
}
public class Hits{
    private int numberOfGames;
    private int prizeAmount;
}

<小时>

我想做的是遍历 arrRound 的所有元素,获取它们的命中字段的 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.

提前感谢您的帮助!

推荐答案

你可以这样实现:

  • 遍历list
  • Round
  • Round 对象更改为它的 List点击次数,
  • 使用flatMapStream>Stream
  • Hits 更改为它的 prizeAmount 字段
  • 获取max(如果存在)
  • 如果没有最大值(如列表为空或其他)返回 -1
  • 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

所以一个使用方法参考

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

lambdamap + flatMap 合二为一:

int maxPrize = arrRoundarrRound.stream()    
                               .flatMap(round -> round.getHits().stream())
                               .mapToInt(hits -> hits.getPrizeAmount())
                               .max()                         
                               .orElse(-1); 

这篇关于使用 Java 8 流方法获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆