首页 > 解决方案 > 从地图中自定义对象内的数组中获取双精度数组

问题描述

我在地图中有一个自定义对象(分配)。我正在寻找地图中每个分配条目的权重列。例如,如果我有 10 个 Map 条目并且每个 Allocation 对象有 3 个权重,我想获得 Java 8 中每个 Map 条目的第 i 个权重。这是我正在寻找的示例。在 Java 8 中执行此操作的任何想法或建议。谢谢!

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)

如果上述 3 个投资组合是 3 个 Map 条目,我想从数组中的 3 个投资组合中的每一个中获取权重:

 first column of weights as

weight[0]=0.3 from portfolio 1
weight[1] = 0.4 from portfolio 2
weight[2] = 0.5 from portfolio 3

第二列权重为:

weight[0] = 0.2 from portfolio 1
weight[1] = 0.4 from portfolio 2
weight[2] = 0.25 from portfolio 3



public class Allocation {
private double returnValue;
private double risk;
private double[] weights;

public Allocation() {
    returnValue = 0;
    risk = 0;
    weights = null;
}

public double getReturnValue() {
    return returnValue;
}

public void setReturnValue(double returnValue) {
    this.returnValue = returnValue;
}

public double getRisk() {
    return risk;
}

public void setRisk(double risk) {
    this.risk = risk;
}

public double[] getWeights() {
    return weights;
}

public void setWeights(double[] weights) {
    this.weights = weights;
}

}

标签: java-8

解决方案


Map<String, Allocation> map = new LinkedHashMap<>();
map.put("portfolio1", a1);
map.put("portfolio2", a2);
map.put("portfolio3", a3);

// Calculate max size of the weights array. Can be omitted if you already know the size.
int maxNumberOfWeights = map.values()
        .stream()
        .mapToInt(allocation -> allocation.getWeights().length)
        .max()
        .getAsInt();

// List of list of columns
List<List<Double>> result = IntStream.range(0, maxNumberOfWeights)
        .mapToObj(idx -> map.values()
                .stream()
                .map(Allocation::getWeights)
                .map(doubles -> doubles.length > idx ? doubles[idx] : 0) // can be just .map(doubles -> doubles[idx]) if the length of all weights arrays will always be the same
                .collect(Collectors.toList()))
        .collect(Collectors.toList());

System.out.println(result);

输出

[[0.3, 0.4, 0.5], [0.2, 0.4, 0.25], [0.5, 0.2, 0.25]]

或者有double[]s 代替,你可以这样做:

List<double[]> result = IntStream.range(0, maxNumberOfWeights)
        .mapToObj(idx -> map.values()
                .stream()
                .map(Allocation::getWeights)
                .mapToDouble(doubles -> doubles.length > idx ? doubles[idx] : 0)
                .toArray())
        .collect(Collectors.toList());
result.forEach(doubles -> System.out.println(Arrays.toString(doubles)));

输出

[0.3, 0.4, 0.5]
[0.2, 0.4, 0.25]
[0.5, 0.2, 0.25]

推荐阅读