有没有一种方法可以并行遍历嵌套列表?

时间:2019-12-08 01:48:03

标签: java loops kotlin stream nested-lists

我将此输入放在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 ,代码可能真的很有帮助。谢谢:)

1 个答案:

答案 0 :(得分:0)

为每个Iterator获取一个List,然后从每个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]
{{1}}