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
JavaScript
x
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.
JavaScript
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,
JavaScript
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + ""));