Reputation: 4380
I have the following map:
AB -> 0.5
AC -> 0.7
AD -> 0.2
B -> 0.3
C -> 0.9
And I now want to map it to this, preferably using Java 8:
A -> (0.5 + 0.7 + 0.2) / 3
B -> 0.3
C -> 0.9
I have tried a combination of collectors and computes, but can never quite get there. The keys should be grouped, if their first character is an 'A' and the value should then be the average of the group. If the key does not start with an 'A', the entry should be kept as is.
Upvotes: 3
Views: 553
Reputation: 137064
You can do that by using the groupingBy(classifier, downstream)
collector that will classify according to the first character of the key and the downstream collector, which is applied on all values classified to same key, would be 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}"
}
Upvotes: 6