例如,我有一个表写入 .txt 文件,例如:
Column_A Column_B
Cell_1 Cell_2
Cell_3 Cell_4
我可以获取单个流管道中的第一行和最后一行吗? 此外,我如何将这些数据收集到地图中,例如:
{ "Column_A": "Cell_3", "Column_B": "Cell_4" }
我目前用普通循环解决这个问题,效果很好,但我想知道是否有另一种使用 Stream API 的解决方案。
我知道如何获取不同流管道的第一行和最后一行。
String[] keys=br.lines().findFirst().get().split(" ");
String[] values=br.lines().reduce((el1,el2)->el2).get().split(" ");
接下来,我可以使用这些数组创建地图。 但正如我所想,这段代码很混乱。
我想知道是否有类似的解决方案:
HashMap<String,String> result = br.lines().filterFirstAndLast().flatMap(el->el.split(" ")) .collect(Collectors.toMap(keys,values))
这是一种方法。 它使用扫描仪读取行,保存列标题,然后跳过其余部分直到最后。 速度肯定会有所不同,但它会在不到 1 秒的时间内读取超过 100 万行。
File f = new File("F:/ColumnData.txt");
Map<String, String> result = getLastLine(f);
result.entrySet().forEach(System.out::println);
打印类似于以下内容的内容:
Column_A=Cell_3
Column_B=Cell_4
public static Map<String, String> getLastLine(File file) {
try (Scanner scanner = new Scanner(file)) {
String[] headers = null;
if (scanner.hasNextLine()) {
headers = scanner.nextLine().split("\\s+");
}
String lastLine = "";
while (scanner.hasNext()) {
lastLine = scanner.nextLine();
}
String[] data = lastLine.split("\\s+");
return Map.of(headers[0], data[0], headers[1], data[1]);
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
}
注意返回的Map是不可修改的。 如果需要修改,可以进行以下操作:
return new HashMap<>(Map.of(headers[0], data[0], headers[1], data[1]));