有没有办法并行迭代嵌套列表?

Is there a way to iterate over nested list in parallel?

我在 HashMap<Int,List<ClassName>>

中有这个输入

1=[100:1.0, 233:0.9,....n],

2=[24:1.0, 13:0.92,....n],

3=[5 : 1000.0, 84 : 901.0,....n],

4=[24: 900.0, 12: 850.0...n],

。 . . //n个条目数

我想把它转换成 [100:1.0,24:1.0,5:1000.0,34:900,233:0.9,13:0.92,84:901.0,12:850.0]

基本都是挑出每个列表相同的索引。我正在使用 Java,代码可能真的很有帮助。谢谢:)

为每个 List 获取一个 Iterator,然后从每个中提取一个值,重复提取直到完成。

像这样:

public final class ClassName {
    private final int a;
    private final double b;
    public ClassName(int a, double b) {
        this.a = a;
        this.b = b;
    }
    @Override
    public String toString() {
        return this.a + " : " + this.b;
    }
}
Map<Integer, List<ClassName>> map = new LinkedHashMap<>();
map.put(1, Arrays.asList(new ClassName(100, 1.0), new ClassName(233, 0.9)));
map.put(2, Arrays.asList(new ClassName(24, 1.0), new ClassName(13, 0.92)));
map.put(3, Arrays.asList(new ClassName(5, 1000.0), new ClassName(84, 901.0)));
map.put(4, Arrays.asList(new ClassName(24, 900.0), new ClassName(12, 850.0)));
map.forEach((k, v) -> System.out.println(k + "=" + v));
List<ClassName> result = new ArrayList<>();
List<Iterator<ClassName>> iterators = map.values().stream()
        .map(List::iterator).collect(Collectors.toList());
while (iterators.stream().anyMatch(Iterator::hasNext))
    iterators.stream().filter(Iterator::hasNext).map(Iterator::next).forEach(result::add);

System.out.println(result);

注意:更改为使用 LinkedHashMap 因此结果将按定义的顺序排列。

输出

1=[100 : 1.0, 233 : 0.9]
2=[24 : 1.0, 13 : 0.92]
3=[5 : 1000.0, 84 : 901.0]
4=[24 : 900.0, 12 : 850.0]
[100 : 1.0, 24 : 1.0, 5 : 1000.0, 24 : 900.0, 233 : 0.9, 13 : 0.92, 84 : 901.0, 12 : 850.0]