通过lambda表达式查找每个类别的最大值之和?
我们有很多像这样的东西-通过lambda表达式查找每个类别的最大值之和?,lambda,java-8,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_
<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>
如何获得每个类别(即行\级)的最大值之和,例如上述示例-
总和=A类(6)的最大值+B类(4)的最大值=10,假设您的分数表示如下:
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;
}
}
int sumMaxs = maxScores.values()
.stream()
.map(s -> s.map(Score::getScoreValue).orElse(0))
.mapToInt(Integer::intValue)
.sum();
您与groupingBy催收员的关系已经很好。只需将空值映射到比较器中的0。comparing():
您的尝试是什么?我正在尝试类似-scores.stream().filter(e->e.getColumnLabel().equalsIgnoreCase(“N/A”)).collect(collector.groupingBy(Score::getRowLabel,Collectors.maxBy(Comparator.comparing(Score::getScoreValue));只是想确保如果任何分数都不存在score_值,它应该将其与0进行比较,而不是与NullPointerException进行比较。您发布的不是分数流。这是一个XML文档。因此,必须有一些代码,您必须将其转换为
流
。在那里编写将不存在scoreValue
转换为0的业务逻辑。同样的分数有两个scoreValue
意味着什么?你应该把你在评论中写的东西放到你的问题中。
int sumMaxs = maxScores.values()
.stream()
.map(s -> s.map(Score::getScoreValue).orElse(0))
.mapToInt(Integer::intValue)
.sum();