2016-11-03 6 views
-1

我々はスコアのストリームオブジェクトがありラムダ式で各カテゴリの最大の和を求めますか?

<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)については、例えばlike-

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; 
    } 
} 

あなたは正しい軌道に乗って、すでにました:カテゴリーAのための 合計=最大上記の例 - のために(6)+カテゴリBの最大(4)次のようにあなたのスコアが表されていると仮定すると、10

+0

あなたの試みは何ですか? – Loc

+0

私は何かlike-scores.stream()を試しています。フィルター(e-> e.getColumnLabel()。equalsIgnoreCase( "N/A")) .collect(Score :: getRowLabel、 Collectors.maxBy (Comparator.comparing(Score :: getScoreValue))))); –

+0

Scoreのいずれにもscore_valueが存在しないようにしたいのですが、NullPointerExceptionの代わりに0と比較する必要があります。 –

答えて

0

= groupingByコレクタで

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() 
          ) 
        ) 
      )); 

をそして最後に、次のように最大値の合計が行うことができます取得:ちょうどComparator.comparing()内部で0にnull値をマッピング

int sumMaxs = maxScores.values() 
     .stream() 
     .map(s -> s.map(Score::getScoreValue).orElse(0)) 
     .mapToInt(Integer::intValue) 
     .sum(); 
関連する問題