AviX
AviX

Reputation: 93

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.

Upvotes: 0

Views: 55

Answers (1)

flopcoder
flopcoder

Reputation: 1175

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());
    }

Upvotes: 1

Related Questions