通过lambda表达式找出每个类别的最大总和?

时间:2016-11-03 15:03:21

标签: lambda java-8

我们有得分流对象,如 -

<Scores>
    <score match_option="any" row_label="A" column_label="1" scoreValue="4"/>
    <score match_option="any" row_label="A" column_label="2" scoreValue="3"/>
    <score match_option="any" row_label="A" column_label="3" scoreValue="2"/>
    <score match_option="any" row_label="A" column_label="4" scoreValue="6"/>
    <score match_option="any" row_label="A" column_label="N/A" scoreValue="1"/>
    <score match_option="any" row_label="B" column_label="1" scoreValue="3"/>
    <score match_option="any" row_label="B" column_label="2" scoreValue="4"/>
    <score match_option="any" row_label="B" column_label="3" scoreValue="1"/>
    <score match_option="any" row_label="B" column_label="4"/>
    <score match_option="any" row_label="B" column_label="N/A" scoreValue="2"/>
</Scores>

如何获得每个类别的最大总和(即row_level),例如以上例子 - Sum =类别A的最大值(6)+类别B的最大值(4)= 10

1 个答案:

答案 0 :(得分:0)

假设您的分数表示如下:

class Score {
    private String matchOption;
    private String rowLabel;
    private String columnLabel;
    private Integer scoreValue;

    public Score(String matchOption, String rowLabel, String columnLabel, Integer scoreValue) {
        this.matchOption = matchOption;
        this.rowLabel = rowLabel;
        this.columnLabel = columnLabel;
        this.scoreValue = scoreValue;
    }

    public String getMatchOption() {
        return matchOption;
    }

    public String getRowLabel() {
        return rowLabel;
    }

    public String getColumnLabel() {
        return columnLabel;
    }

    public Integer getScoreValue() {
        return scoreValue;
    }
}

您已经使用groupingBy收藏家走上了正确的轨道。只需将Comparator.comparing()内的空值映射为0:

 Map<String, Optional<Score>> maxScores = scores.stream()
    .filter(e -> !e.getColumnLabel().equalsIgnoreCase("N/A"))
    .collect(
             Collectors.groupingBy(
                    Score::getRowLabel,
                    Collectors.maxBy(
                            Comparator.comparing(
                                    s -> s.getScoreValue() == null ? 0 : s.getScoreValue()
                            )
                    )
            ));

最后获得最大值的总和可以按如下方式完成:

int sumMaxs = maxScores.values()
        .stream()
        .map(s -> s.map(Score::getScoreValue).orElse(0))
        .mapToInt(Integer::intValue)
        .sum();