我的数据是这样的,
unitId time value1 value2
a 2021 10 11
a 2022 15 13
b 2021 20 25
b 2022 30 37
我的目标是把每一个单位和价值都放到这样的 map 上,
{
'a': {'2021_value1': 10, '2021_value2': 11, '2022_value1': 15, '2022_value2': 13},
'b': {'2021_value1': 20, '2021_value2': 25, '2022_value1': 30, '2022_value2': 37},
}
我已经想出了两种方法来实现这一点,这是我的代码,
public class Unit {
public String unitId;
public Integer year;
public Integer value1;
public Integer value2;
public static Unit of(String unitId, Integer year, Integer value1, Integer value2) {
Unit unit = new Unit();
unit.unitId = unitId;
unit.year = year;
unit.value1 = value1;
unit.value2 = value2;
return unit;
}
}
和
public class UnitTest {
private static void printMap(Map<String, Map<String, Integer>> map) {
map.forEach((k, v) -> {
String vStr = v.entrySet().stream().map(a -> String.format("%s: %s", a.getKey(), a.getValue())).collect(Collectors.joining(", "));
System.out.printf("%s: {%s}%n", k, vStr);
});
}
public static void main(String[] args) {
List<Unit> list = new ArrayList<>();
list.add(Unit.of("a", 2021, 10, 11 ));
list.add(Unit.of("a", 2022, 15, 13));
list.add(Unit.of("b", 2021, 20, 25));
list.add(Unit.of("b", 2022, 30, 37));
Map<String, Map<String, Integer>> map1 = list.stream().collect(
Collectors.groupingBy(
x -> x.unitId,
Collector.of(
HashMap::new,
(x, y) -> {
x.put(String.format("%s_%s", y.year, "value1"), y.value1);
x.put(String.format("%s_%s", y.year, "value2"), y.value2);
},
(x, y) -> {x.putAll(y); return x;}
)
)
);
Map<String, Map<String, Integer>> map2 = list.stream().collect(
Collectors.groupingBy(
x -> x.unitId,
Collectors.collectingAndThen(
Collectors.toList(),
x -> x.stream()
.flatMap(y -> Stream.of(
new AbstractMap.SimpleEntry<>(String.format("%s_%s", y.year, "value1"), y.value1),
new AbstractMap.SimpleEntry<>(String.format("%s_%s", y.year, "value2"), y.value2)
))
.collect(Collectors.toMap(
AbstractMap.SimpleEntry::getKey,
AbstractMap.SimpleEntry::getValue)))
)
);
printMap(map1);
printMap(map2);
}
}
第一种方法更像是手动编写处理,第二种方法使用临时列表,这可能不是必需的.有没有什么直接或简单的方法可以做到这一点,比如使用Collectors.toMap API或其他什么?