【问题标题】:Is there a way to iterate over nested list in parallel?有没有办法并行迭代嵌套列表?
【发布时间】:2019-12-08 01:48:03
【问题描述】:

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

【问题讨论】:

  • 你必须试一试,问题仍然不清楚你的类模型是什么以及你期望的输出类型是什么。是HashMap 还是List<ClassName>
  • 此外,您的示例重复了密钥24,并且似乎在“我想将其转换为”部分中完全忽略了这一点,并使用了“第一个”。这是预期的行为吗?如果您并行迭代,“第一个”变得更难跟踪。
  • 如果你想用 Java 得到答案,为什么用 Kotlin 标记?

标签: java loops kotlin stream nested-lists


【解决方案1】:

为每个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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2020-10-20
    • 2014-03-23
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多