Java 8, how can I implement a switch statement using streams?

前端 未结 4 1680
忘掉有多难
忘掉有多难 2020-11-28 15:08

I have a text file imgui.ini containing:

[Debug]
Pos=7,79
Size=507,392
Collapsed=0

[ImGui Demo]
Pos=320,5
Size=550,680
Collapsed=0
4条回答
  •  鱼传尺愫
    2020-11-28 16:00

    Another way to read your config file:

    public class Main {
        public static void main(String[] args) throws IOException {
            Path path = Paths.get("D:\\Development\\workspace\\Application\\src\\main\\resources\\init.txt");
            String content = new String(Files.readAllBytes(path));
    
            Map configMap = Stream.of(content.split("\\n\\r"))
                .map(config -> Arrays.asList(config.split("\\r")))
                .collect(HashMap::new, (map, list) -> {
                    String header = list.get(0);
                    String pos = list.get(1);
                    String size = list.get(2);
                    String collapsed = list.get(3);
                    map.put(header, new Config(pos.substring(pos.indexOf("=") + 1), size.substring(size.indexOf("=") + 1), collapsed.substring(collapsed.indexOf("=") + 1)));
                }, (m, u) -> {});
    
            System.out.println(configMap);
        }
    }
    
    class Config {
        public String pos;
        public String size;
        public String collapsed;
    
        public Config(String pos, String size, String collapsed) {
            this.pos = pos;
            this.size = size;
            this.collapsed = collapsed;
        }
    
        @Override
        public String toString() {
            return "Config{" +  "pos='" + pos + '\'' + ", size='" + size + '\'' + 
                   ", collapsed='" + collapsed + '\'' + '}';
        }
    }
    

    Result will be map:

    {
        [Debug]=Config{pos='7,79', size='507,392', collapsed='0'}, 
        [ImGui Demo]=Config{pos='320,5', size='550,680', collapsed='0'}
    }
    

提交回复
热议问题