简体   繁体   中英

split a String into String(containing some special character) and Integer in Java

I have two String like

a 101 or [newline] 111

Need to put these in a HashMap where string [newline] and other String 'a' as key and Integer 111 as value of key.

Note : valid space between a and 101. and '[newline]' also should be considered as string.

Try this using regex. I think it will serve your purpose.

   public static void main(String[] args) {
        String[] s = {"a    101","[newline]      111"};
        Map<String, Integer> map = new HashMap<>();
        for(int i=0;i<s.length;i++) {
            String[] splitedData = s[i].split("\\s+");
            map.put(splitedData[0], Integer.valueOf(splitedData[1].trim()));
        }
        for (Map.Entry<String,Integer> entry : map.entrySet())
            System.out.println("Key = " + entry.getKey() +
                    ", Value = " + entry.getValue());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM