如何通过lambda表达式将List<List>解析为ArrayList<HashMap>?

How can I parse List<List> into ArrayList<HashMap> through lambda expression?

也许这是一个非常愚蠢的问题,但我找不到任何解决方案。我是 lambda 的新手,我正在尝试使用它来将列表 <List> 解析为 ArrayList <HashMap>.

最初我从 csv 文件中解析出一个数据集,然后将它们的每一行变成一个列表,并将它们添加到我上面提到的列表 <'List'> 中。因为我必须在此之后过滤它们,所以我想将它们的每一行更改为 HashMap<columnName, columnValue>,但是当我尝试这样做时,它 returns 什么都没有。

这是我的代码:

// import data from csv file
private static List<List> readWholeFile(BufferedReader br) throws IOException {
    List<List> rows = new ArrayList<>();
    String line = br.readLine();

    try {
        if (line != null) {
            String[] test = line.split(",");
            List<String> row = Arrays.asList((String[]) line.split(","));
            rows.add(row);
            return readWholeFile(br);
        }
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    } finally {
        return rows;
    }
}

//parse List<List> into ArrayList<HashMap>
private static ArrayList<HashMap> putRowIntoMap(List<List> rows, List<String> columns) {
    ArrayList<HashMap> itemMap = new ArrayList<>();
    List<HashMap> test = new ArrayList<>();
    HashMap<String, String> eleMap = new HashMap<>();
    rows.stream().map(row -> (row.stream().map(ele -> eleMap.put(keys.get(row.indexOf(ele)), (String) ele))))
            .collect(Collectors.toCollection(ArrayList::new));
    itemMap.add(eleMap);
    System.out.println(eleMap);  //output: {}

    return itemMap;
}
  1. 使用 NIO Files.lines 将输入文件读入 List<List<String>> 将文本文件的行返回为 Stream<String>
public static List<List<String>> readFile(String filename) throws IOException {
    return Files.lines(Paths.get(filename)) // Stream<String>
        .map(line -> Arrays.asList(line.split(","))) // Stream<List<String>>
        .collect(Collectors.toList());               // List<List<String>>
}
  1. List<String>的列表转换为map,假设columnNamesrows中的列表具有相同的索引,并且所有列名都不同。
public static List<Map<String, String>> intoMap(List<List<String>> rows, List<String> columnNames) {
    return rows.stream() // Stream<List<String>>
        .map(row -> IntStream.range(0, row.size()) // IntStream
            .boxed() // Stream<Integer>
            .collect(Collectors.toMap(
                i -> columnNames.get(i), // key: columnName
                i -> row.get(i)          // value
                // ,(r1, r2) -> r1,       // placeholder for merge function
                // LinkedHashMap::new    // supplier of LinkedHashMap
            )) // Map<String, String>
        ) // List<Map<String, String>>
        .collect(Collectors.toList());
}

默认情况下,Collectors.toMap returns 一个未排序的 HashMap 实现,因此使用 LinkedHashMap 维护插入顺序(如果需要,两个toMap 中的注释行应取消注释)。