Posts

Showing posts with the label Java Program To Convert String To HashMap

Java Program To Convert String To HashMap

Example 1: Convert  below String String str = "{name = rahul,email = rahul@knf.co.in,gender = male}" ; to HashMap Solution 1:   public static void main( String [] args) { String str = "{name = rahul,email = rahul@knf.co.in,gender = male}" ; //Remove curly brackets. str = str.substring( 1 , str.length() - 1 ); //Split the string by , to get key-value pairs String [] keyValuePairs = str.split( "," ); Map < String , String > map = new HashMap <>(); //Iterate over the pairs for ( String pair : keyValuePairs) { //Split the pairs to get key and value String [] entry = pair.split( "=" ); //Add them to the hashmap and trim whitespaces map.put(entry[ 0 ].trim(), entry[ 1 ].trim()); } System.out.println(map); } Solution 2: Using Java 8 Stream public static void main( String [] a