计算列表列表中的对象属性总和(带流)

时间:2015-03-04 11:05:06

标签: java list java-8

我使用的是Java 8,我希望使用List.stream()功能来解决我的问题。

这是我的问题:

这是Score类(Player类并不重要):

public class Score {

    private Player player;
    private int score;

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

在我的计划开始时,我有一个填充的玩家列表:

List<Player> players; // Populated elsewhere

我的程序然后做它必须做的事情,我得到一个这种类型的变量:

List<List<Score>> scores; // Populated elsewhere

现在我想为每个玩家打印一个格式化的输出:

Player.getName() + " : " + averagedScore;

其中averagedScore是一个score.getScore()的{​​{1}}值之和除以Player个变量中此玩家得分的出现次数。


现在,我到目前为止做了什么:

scores

但我不知道如何计算子列表中包含的for (Players player : players) { scores.stream().filter(x -> x.stream().anyMatch(y -> y.getPlayer().equals(player))); } 的总和并按element.getScore()过滤

1 个答案:

答案 0 :(得分:5)

您可以在使用&#34; flatMapped&#34;之后使用groupingByaveragingInt收藏家的组合你的清单清单:

Map<Player, Double> scoreByPlayer = scores.stream()
                .flatMap(List::stream)
                .collect(groupingBy(Score::getPlayer, averagingInt(Score::getScore)));

scoreByPlayer.forEach((p, s) -> System.out.println(p + " : " + s));

注意:需要以下静态导入:

import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.groupingBy;


供参考,完整示例:

public static void main(String[] args) {
  Player adam = new Player("Adam");
  Player pat = new Player("Pat");
  Player susie = new Player("Susie");
  List<List<Score>> scores = new ArrayList<> ();
  scores.add(Arrays.asList(s(adam, 1), s(pat, 2), s(susie, 3)));
  scores.add(Arrays.asList(s(adam, 2), s(pat, 4), s(susie, 6)));
  scores.add(Arrays.asList(s(adam, 3), s(pat, 6), s(susie, 9)));

  Map<Player, Double> scoreByPlayer = scores.stream()
                  .flatMap(List::stream)
                  .collect(groupingBy(Score::getPlayer, averagingInt(Score::getScore)));

  scoreByPlayer.forEach((p, s) -> System.out.println(p + " : " + s));
}

private static Score s(Player p, int score) { return new Score(p, score); }

public static class Score {
  private final Player player;
  private final int score;
  public Score(Player player, int score) {
    this.player = player;
    this.score = score;
  }

  public Player getPlayer() { return player; }
  public int getScore() { return score; }
}

public static class Player {
  private final String name;
  public Player(String name) { this.name = name; }
  @Override public String toString() { return name; }
}