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
}
We can also convert an array of String to a HashMap. Suppose we have a string array of the student name and an array of roll numbers, and we want to convert it to HashMap so the roll number becomes the key of the HashMap and the name becomes the value of the HashMap. Note: Both the arrays should be the same size.
Strings can be converted to integers by using the int() method. If your string does not have decimal places, you'll most likely want to convert it to an integer by using the int() method.
We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.
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) + ""));
You can write like
String str = "abcd";
Map<Integer, Character> map = IntStream.range(0, str.length()).boxed()
.collect(Collectors.toMap(Function.identity(), pos -> str.charAt(pos)));
No need to split the String with String[] strings = str.split("");
A simple one-liner.
You can do it without the counter as:
String str = "abcd";
Map<Integer,String> map = new HashMap<>();
String[] strings = str.split("");
for(int i=0;i<strings.length;i++) {
map.put(i, strings[i]);
}
map.forEach((k,v)->System.out.println(k+" "+v));
Another way around, credit @Holger
for(String s: strings) {
map.put(map.size(), s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With