有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带流的java ArrayList迭代

我有一份清单。我需要根据索引从这些列表中提取项目,并使其成为单独的arraylist。我试着通过添加

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对象存储,而是将所有项组合在一起。你能纠正我哪里做错了吗

谢谢


共 (1) 个答案

  1. # 1 楼答案

    此操作:

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

    通过反转过滤器和映射,可以避免重复get:

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