Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to Map<Integer,String> 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
}
like image 531
Rahul Gupta Avatar asked Feb 20 '19 06:02

Rahul Gupta


People also ask

Can I convert a string to map in java?

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.

Can you convert strings into integers?

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.

Can I typecast string to int in java?

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.


3 Answers

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) + "")); 
like image 99
Ravindra Ranwala Avatar answered Sep 26 '22 16:09

Ravindra Ranwala


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.

like image 22
Mohamed Anees A Avatar answered Sep 24 '22 16:09

Mohamed Anees A


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);
 }
like image 20
Vishwa Ratna Avatar answered Sep 26 '22 16:09

Vishwa Ratna