gpt4 book ai didi

Java:将多个列表组合到一个列表中

转载 作者:行者123 更新时间:2023-12-01 07:25:50 26 4
gpt4 key购买 nike

有没有快速获取 List< List<Double> > 的方法并对它们进行平均,这样我只有一个 Double 列表,其中每一列是该列中所有原始列表的平均值?

最佳答案

使用 Java 8,你可以编写类似这样的东西 - 但它并不是很短......

List<List<Double>> list = Arrays.asList(Arrays.asList(1d, 2d, 3d),
Arrays.asList(2d, 3d, 4d, 5d));

//the largest list size
int maxSize = list.stream().mapToInt(List::size).max().orElse(0);

//for each index in the final list, we calculate the average across "valid" lists
//i.e. lists that are large enough
List<Double> averages = IntStream.range(0, maxSize)
.mapToObj(i -> list.stream()
.filter(sublist -> sublist.size() > i)
.mapToDouble(sublist -> sublist.get(i))
.average().getAsDouble())
.collect(toList());

//prints averages = [1.5, 2.5, 3.5, 5.0]
System.out.println("averages = " + averages);

关于Java:将多个列表组合到一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com