有条件地组映射条目 - Java 8

Aer*_*rus 3 java java-8 java-stream

我有以下地图:

AB -> 0.5
AC -> 0.7
AD -> 0.2
B  -> 0.3
C  -> 0.9
Run Code Online (Sandbox Code Playgroud)

我现在想要将它映射到此,最好使用Java 8:

A  -> (0.5 + 0.7 + 0.2) / 3
B  -> 0.3
C  -> 0.9
Run Code Online (Sandbox Code Playgroud)

我尝试过收藏家和计算机的组合,但是永远不会到达那里.如果键的第一个字符是'A',那么键应该被分组,然后该值应该是该组的平均值.如果密钥不以"A"开头,则该条目应保持原样.

Tun*_*aki 5

您可以使用groupingBy(classifier, downstream)将根据键的第一个字符进行分类的收集器和下游收集器(将应用于分类到相同键的所有值)进行分类averagingDouble.

public static void main(String[] args) {
    Map<String, Double> map = new HashMap<>();
    map.put("AB", 0.5);
    map.put("AC", 0.7);
    map.put("AD", 0.2);
    map.put("B", 0.3);
    map.put("C", 0.9);

    Map<Character, Double> result =
        map.entrySet()
           .stream()
           .collect(Collectors.groupingBy(
             e -> e.getKey().charAt(0),
             Collectors.averagingDouble(Map.Entry::getValue)
           ));

    System.out.println(result); // prints "{A=0.4666666666666666, B=0.3, C=0.9}"
}
Run Code Online (Sandbox Code Playgroud)