【问题标题】:ArrayList iteration with Streams使用 Streams 进行 ArrayList 迭代
【发布时间】:2018-09-17 18:23:33
【问题描述】:

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

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 对象存储,它正在组合所有项目。你能纠正我错的地方吗?

谢谢

【问题讨论】:

  • List&lt;List&lt;String&gt; = totalRecords; 这在语法上不准确
  • 请提供minimal reproducible example。您当前的代码 sn-p 有许多语法错误,使您难以理解您要执行的操作。确保在您的代码周围包含一个类和方法,以便我们可以复制并粘贴它来自己编译。
  • 应该是 List totalRecords = totalRecordsList;
  • flatMap 就是这样做的,它将列表列表扁平化为一维列表。删除该方法调用。
  • 你的意思是map(e -&gt; e.get(index))而不是flatMap?

标签: java arraylist java-8 java-stream


【解决方案1】:

这个操作:

.flatMap(List::stream)

将输入列表中的所有内容扁平化为流。

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

.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))

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 2012-01-16
    • 1970-01-01
    • 2014-03-26
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多