我有一些哈希映射,如下所示。我想将这些地图合并到一个嵌套的地图中。
public class MyClass {
public static void main(String[] args) {
HashMap<String, Capacity> capacityMap1 = new HashMap<>();
capacityMap1.put("BMW", new Capacity(10.0, 0.0));
capacityMap1.put("Audi", new Capacity(20.0, 10.0));
capacityMap1.put("Toyota", new Capacity(50.0, 0.0));
HashMap<String, Capacity> capacityMap2 = new HashMap<>();
capacityMap1.put("BMW", new Capacity(0.0, 10.0));
capacityMap1.put("Audi", new Capacity(80.0, 0.0));
capacityMap1.put("Toyota", new Capacity(90.0, 0.0));
HashMap<String, Capacity> capacityMap3 = new HashMap<>();
capacityMap1.put("BMW", new Capacity(30.0, 0.0));
HashMap<String, Capacity> capacityMap4 = new HashMap<>();
capacityMap1.put("Audi", new Capacity(80.0, 0.0));
capacityMap1.put("Toyota", new Capacity(90.0, 10.0));
}
enum UsageConsumed {
Inbound,
OutBound,
}
static class Capacity {
double inBoundCapacity;
double outBoundcapacit;
public Capacity(double inBoundCapacity, double outBoundcapacit) {
this.inBoundCapacity = inBoundCapacity;
this.outBoundcapacit = outBoundcapacit;
}
}
}
我想创建一个嵌套的地图列表HashMap
答案 0 :(得分:0)
我认为应该这样做:
public static Map<String, HashMap<UsageConsumed, Double>> buildNestedMap(HashMap<String, Capacity>... maps) {
Map<String, HashMap<UsageConsumed, Double>> result = Stream.of(maps)
// get a stream of all the map entries
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
// create the value for a single entry
entry -> {
HashMap<UsageConsumed, Double> usageConsumedMap = new HashMap<>();
usageConsumedMap.put(UsageConsumed.Inbound, entry.getValue().inBoundCapacity);
usageConsumedMap.put(UsageConsumed.OutBound, entry.getValue().outBoundcapacit);
return usageConsumedMap;
},
// merge the values between entries with the same key
(a, b) -> {
a.merge(UsageConsumed.Inbound, b.get(UsageConsumed.Inbound), Double::sum);
a.merge(UsageConsumed.OutBound, b.get(UsageConsumed.OutBound), Double::sum);
return a;
}
));
return result;
}
经过以下代码测试:
public static void main(String[] args) {
HashMap<String, Capacity> capacityMap1 = new HashMap<>();
capacityMap1.put("BMW", new Capacity(10.0, 0.0));
capacityMap1.put("Audi", new Capacity(20.0, 10.0));
capacityMap1.put("Toyota", new Capacity(50.0, 0.0));
HashMap<String, Capacity> capacityMap2 = new HashMap<>();
capacityMap2.put("BMW", new Capacity(0.0, 10.0));
capacityMap2.put("Audi", new Capacity(80.0, 0.0));
capacityMap2.put("Toyota", new Capacity(90.0, 0.0));
HashMap<String, Capacity> capacityMap3 = new HashMap<>();
capacityMap3.put("BMW", new Capacity(30.0, 0.0));
HashMap<String, Capacity> capacityMap4 = new HashMap<>();
capacityMap4.put("Audi", new Capacity(80.0, 0.0));
capacityMap4.put("Toyota", new Capacity(90.0, 10.0));
Map<String, HashMap<UsageConsumed, Double>> result = buildNestedMap(capacityMap1, capacityMap2, capacityMap3, capacityMap4);
System.out.println(result);
}
输出为:
{Toyota={Inbound=230.0, OutBound=10.0}, Audi={Inbound=180.0, OutBound=10.0}, BMW={Inbound=40.0, OutBound=10.0}}