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

查看:2327
本文介绍了使用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<Hit> hits
  • 一个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的所有元素,获取其hits字段的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.

谢谢您的帮助!

推荐答案

您可以通过以下方式实现:

You can achieve it by this way :

  • 遍历list
  • Round
  • Round对象更改为其List<Hit> hits
  • 使用flatMapStream<List<Hits>>转到Stream<Hits>
  • 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

所以使用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

其中一个类为lambdamap + flatMap:

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

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

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