How to add values in duplicated key Map in Java 8
You should declare a merging strategy in the first stream:
.collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1]), Double::sum));
and then filtered Map by zero value:
.filter(s-> s.getValue() != 0)
for sorting by key use:
.sorted(Map.Entry.comparingByKey())
result code:
String [] 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]), Double::sum));
kvs.entrySet().stream()
.filter(s-> s.getValue() != 0)
.sorted(Map.Entry.comparingByKey())
.forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());w
});
It's working for me , I used Integer instead of double and summaringInt()
function for sum values with same key:
String[] strArr = new String[] { "X:-1", "Y:1", "X:-4", "B:3", "X:5" };
Map<String, IntSummaryStatistics> collect = Arrays.asList(strArr)
.stream()
.map(elem -> elem.split(":"))
.collect(Collectors.groupingBy(e -> e[0], Collectors.summarizingInt(e -> Integer.parseInt(e[1]))));
System.out.println("Result:");
collect.entrySet().stream()
.filter(e -> e.getValue().getSum() != 0)
.sorted(Map.Entry.comparingByKey())
.forEach(e -> System.out.println("Key : " + e.getKey() + ", Value : " + e.getValue().getSum()));
It is also possible to use Collectors.groupingBy
+ Collectors.summingDouble
to build a sorted kvs
map by collecting to TreeMap
:
String [] strArr = new String[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"};
Map<String, Double> kvs = Arrays.stream(strArr)
.map(elem -> elem.split(":"))
.collect(Collectors.groupingBy(
e -> e[0],
TreeMap::new, // sort by key
Collectors.summingDouble(e -> Double.parseDouble(e[1]))
));
System.out.println(kvs); // entries with 0 value yet to be removed
// output
// {B=3.0, X=0.0, Y=1.0}
If it is required just to print the map in the mentioned format without 0 values, it may be done like this:
System.out.println(
kvs.entrySet().stream()
.filter(e -> e.getValue() != 0)
.map(e -> new StringBuilder(e.getKey()).append(':').append(e.getValue().intValue()) )
.collect(Collectors.joining(","))
);
// output
// B:3,Y:1
If 0 values need to be removed from kvs
, a removeIf
may be applied to its entry set:
kvs.entrySet().removeIf(e -> e.getValue() == 0);
System.out.println(kvs);
// output
// {B=3.0, Y=1.0}