Stream - Collect by property and max

前端 未结 3 1022
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 09:15

Problem Statement

Given the following class (simplified for the question):

public static class Match {

  private final String type;
  private fina         


        
3条回答
  •  醉酒成梦
    2021-01-18 10:11

    Try to use a TreeMap for this :

    UPDATE

    List matchStream1 = matchStream.
                collect(Collectors.groupingBy(Match::getType,
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Match::getScore)))))
                .values()
                .stream()
                .map(TreeSet::last)
                .collect(Collectors.toList());
    

    In case your Match class implements Comparable. You can simplify this:

    () -> new TreeSet<>(Comparator.comparing(Match::getScore))
    

    to this:

    TreeSet::new
    

提交回复
热议问题