gpt4 book ai didi

java - 使用 Streams 进行 ArrayList 迭代

转载 作者:行者123 更新时间:2023-12-02 01:55:30 24 4
gpt4 key购买 nike

我有列表列表。我需要根据索引从这些列表中提取项目并将其设为单独的数组列表。我尝试通过添加来做到这一点

List<List<String>> multilist = new ArrayList<>();

List<List<String>> totalRecords= totalRecordsList;

List<String> targetList = totalRecords.stream().filter(e ->
e.get(index)!=null).flatMap(List::stream) .collect(Collectors.toCollection(ArrayList::new));

multilist.add(targetList);

但仍然在列表列表中,而不是存储为单独的 arraylist 对象,它组合了所有项目。有错误的地方请大家指正。

谢谢

最佳答案

此操作:

.flatMap(List::stream)

将输入列表中的所有内容压平到流中。

如果您只想获取每个列表的第 index 元素,请将其替换为:

.map(e -> e.get(index))

总体:

totalRecords.stream()
.filter(e -> e.get(index)!=null)
.map(e -> e.get(index))
.collect(Collectors.toCollection(ArrayList::new))

您可以通过反转过滤器和映射来避免重复获取:

totalRecords.stream()
.map(e -> e.get(index))
.filter(Object::nonNull)
.collect(Collectors.toCollection(ArrayList::new))

关于java - 使用 Streams 进行 ArrayList 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52373698/

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