Skip to content
Advertisement

Converting string to Map in java 8

Can someone please guide me on how to achieve the below using Java 8. I don’t know how to get that counter as the key

String str = "abcd";

Map<Integer,String> map = new HashMap<>();

String[] strings = str.split("");

int count =0;
for(String s:strings){
    map.put(count++, s);// I want the counter as the key
}

Advertisement

Answer

You can use IntStream to get this thing done. Use the integer value as the key, and the relevant value in the string array at that index as the value of the map.

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> strings[i]));

Another alternative that obviates the need of split would be,

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + "")); 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement