我在Map中有一个自定义对象:下面是结构
Allocation {
double risk;
double[] weights;
double returnValue;
}
我有一个分配对象的Map,例如:
Map<String, Allocation>
我想用Java8获得二维数组中的权重。
weights={{.3,.2,0.5},{0.4,0.4,0.2},{0.5,0.25,0.25},...}
Allocation Map包含许多如下所示的Portfolio对象:
key: portfolio1, Object: (risk=0.03, weights={0.3,0.2,0.5}, returnvalue=0.5)
Key: portfolio2, Object: (risk=0.05, weights={0.4,0.4,0.2}, returnvalue=0.3)
Key: portfolio3, Object: (risk=0.01, weights={0.5, 0.25, 0.25}, return=0.6)
我想得到一个二维权重数组:
weights[0] = {0.3,0.2,0.5}
weights[1] = {0.4,0.4,0.2}
weights[1] = {0.5, 0.25, 0.25} and so on...
寻找最好的方法,谢谢!
发布于 2020-05-12 06:25:43
只需对值使用map
:
double[][] weights =
map.values()
.stream()
.map(Allocation::getWeights)
.toArray(double[][]::new);
发布于 2020-05-12 06:26:07
像这样试一下。
Map<String, Allocation> map = new HashMap<>();
Allocation a = new Allocation();
a.weights = new double[]{10.0,12.0};
Allocation b = new Allocation();
b.weights = new double[]{20.0,32.0};
map.put("A",a);
map.put("B",b);
double weights[][] = map.values()
.stream()
.map(obj->obj.weights)
.toArray(double[][]::new);
System.out.println(Arrays.deepToString(weights));
打印
[[10.0, 12.0], [20.0, 32.0]]
注意,因为您的Allocation
类没有getter,所以我在解决方案中使用了obj->obj.weights
而不是Allocation::getWeights
来匹配您定义的类。
https://stackoverflow.com/questions/61740190
复制相似问题