将具有结构文本的地图文件转换为实际的HashMap

我下面有这个文件,每行都有一个类似地图的结构

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

如何使用Java 8流读取文件并将每一行转换为地图?预先谢谢你。

zhoulang914 回答:将具有结构文本的地图文件转换为实际的HashMap

创建一行行,每行之间用逗号分隔,然后按“ =”分隔并收集到地图中。然后将地图收集到列表中。例如:

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);
本文链接:https://www.f2er.com/3127735.html

大家都在问