我有一个包含ff数据的2列列表:
-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"
我尝试使用for循环,并在类型相同时添加金额。这可能是for循环还是有更好的方法。
for (int i = 0; i < vecRow.size(); i++) {
// Do something
}
答案 0 :(得分:1)
在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));
或部分更好地理解
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));
因为明显需要精确的,所以不能使用double
,因此:BigDecimal
。
Collectors.mapTo
这里有关键映射器,值映射器和 - 需要求和 - BigDecimal combiner(BigDecimal, BigDecimal)
。
type3=-8875.570000000000
type2=-31851.890000000000
type1=-36745.370000000000