Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object.
In order to convert strings to HashMap, the process is divided into two parts:
- The input string is converted to an array of strings as output.
- Input as an array of strings is converted to HashMap.
Input string elements as follows:
Input : "Aashish:1, Bina:2, Chintu:3"
Approach :
- Phase 1: The input string is converted to an array of strings as output.
- Phase 2: Input as an array of strings is converted to HashMap.
Phase 1:
- First, we split the String by a comma and store it in an array parts. After the split we have the following content:
"Aashish:1","Bina:2", "Chintu:3"
- And then iterate on parts and split the student data to get the student name and roll number. And set roll no as key and the name as the value of the HashMap.
Phase 2:
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.
Input array of string elements as follows which will be output in phase 1
String stuName[] = {"Aashish","Bina","Chintu"}
Integer stuRollNo[] = {1,2,3}
Approach :
- Iterate over the array and set the roll number as key and the name as values in the HashMap.
Phase 1 – String to Array of string
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
String student = "Aashish:1, Bina:2, Chintu:3" ;
Map<String, String> hashMap
= new HashMap<String, String>();
String parts[] = student.split( "," );
for (String part : parts) {
String stuData[] = part.split( ":" );
String stuRollNo = stuData[ 0 ].trim();
String stuName = stuData[ 1 ].trim();
hashMap.put(stuRollNo, stuName);
}
System.out.println( "String to HashMap: " + hashMap);
}
}
|
OutputString to HashMap: {Chintu=3, Bina=2, Aashish=1}
Phase 2 – String to Array to HashMap
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
String stuName[] = { "Aashish" , "Bina" , "Chintu" };
Integer stuRollNo[] = { 1 , 2 , 3 };
Map<Integer, String> hashMap
= new HashMap<Integer, String>();
for ( int i = 0 ; i < stuName.length; i++) {
hashMap.put(stuRollNo[i], stuName[i]);
}
System.out.println( "String to hashmap: " + hashMap);
}
}
|
OutputString to hashmap: {1=Aashish, 2=Bina, 3=Chintu}