I want to add values in duplicated key Map in Java 8.
As an example:
For example: if strArr is ["B:-1", "A:1", "B:3", "A:5"] then my program should return the string A:6,B:2.
My final output string should return the keys in alphabetical order. Exclude keys that have a value of 0 after being summed up.
Input: new String[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"}
Output: B:3,Y:1
Input: new String[] {"Z:0", "A:-1"}
Output: A:-1
Tried code:
public static String Output(String[] strArr) {
//strArr = new String[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"};
Map<String, Double> kvs =
Arrays.asList(strArr)
.stream()
.map(elem -> elem.split(":"))
.collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1])));
kvs.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
return strArr[0];
}
Error:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key -1.0
How can I fix this?