In java 8:
Stream.of("-4123.800000000000;\"type1\"",
"-67.620000000000;\"type2\"",
"-3128.870000000000;\"type2\"",
"-2443.770000000000;\"type1\"",
"-30000.000000000000;\"type1\"",
"-812.580000000000;\"type3\"",
"-8062.990000000000;\"type3\"",
"-177.800000000000;\"type1\"",
"-28655.400000000000;\"type2\"")
.map((s) -> s.split(";", 2))
.collect(Collectors.toMap(
(fields) -> fields[1].replace("\"", ""),
(fields) -> new BigDecimal(fields[0]),
(oldValue, newValue) -> newValue.add(oldValue)))
.entrySet()
.forEach((s) -> System.out.println(s));
Or in parts to better understand
String[] vecRow = {
"-4123.800000000000;\"type1\"",
"-67.620000000000;\"type2\"",
"-3128.870000000000;\"type2\"",
"-2443.770000000000;\"type1\"",
"-30000.000000000000;\"type1\"",
"-812.580000000000;\"type3\"",
"-8062.990000000000;\"type3\"",
"-177.800000000000;\"type1\"",
"-28655.400000000000;\"type2\"",
};
Map<String, BigDecimal> map = Stream.of(vecRow)
.map((s) -> s.split(";", 2))
.peek((ss) -> System.out.println(Arrays.toString(ss)))
.collect(Collectors.toMap(
(fields) -> fields[1].replace("\"", ""),
(fields) -> new BigDecimal(fields[0]),
(oldValue, newValue) -> newValue.add(oldValue)));
map.entrySet()
.forEach((s) -> System.out.println(s));
For the evident desire to have a precision one cannot use double
, hence: BigDecimal
.
Collectors.mapTo
here has key mapper, value mapper and - needed to sum - a BigDecimal combiner(BigDecimal, BigDecimal)
.
type3=-8875.570000000000
type2=-31851.890000000000
type1=-36745.370000000000