将具有类似映射的结构文本的文件转换为实际的HashMap



我下面有一个文件,它在的每一行中都有一个类似映射的结构

sampledatamap.txt
field1=value1,  field2=value2,  field3=value3 ...
field1=value10, field2=value11, field3=value12 ...

如何使用Java8流读取文件并将每一行转换为映射?提前谢谢。

创建一个行流,用逗号分隔每个行,然后用'='分隔,并收集到Map中。然后将地图收集到列表中。例如:

public class Parser {
public static void main(String[] args) throws IOException {
Path path = Paths.get("sampledatamap.txt");
try(Stream<String> lines = Files.lines(path)) {
List<Map<String, String>> collect = lines
.map(Parser::toMap)
.collect(Collectors.toList());
System.out.println(collect);
}
}
static Map<String, String> toMap(String line) {
return Stream
.of(line.split(","))
.map(s -> s.split("="))
.collect(Collectors.toMap((String[] s) -> s[0], (String[] s) -> s[1]));
}
}

这可能不是最干净的解决方案,但这个想法已经被证明了。

List<Map<String, String>> result = Files.readAllLines(Paths.get("sampledatamap.txt"))
.stream()
// transform each line into a stream of "field=value" format
.map(lineStr -> Stream.of(lineStr.split(",")))
.map(line -> line
// transform each of "field=value" format into a Map
.map(rawStr -> {
Map<String, String> entry = new HashMap<>();
String[] kv = rawStr.trim().split("=");
entry.put(kv[0], kv[1]);
return entry;
})
// merge all the single entry map into a full map
.reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
}))
.collect(Collectors.toList());
System.out.println(result);

最新更新