Java Program To Convert String To HashMap

Example 1: Convert below String to HashMap

String str = "{name = rahul,email = rahul@knf.co.in,gender = male}";


Solution 1: Before Java 8 

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[] args) {

String str = "{name = rahul,email = rahul@knf.co.in,gender = male}";
Map<String, String> map = Arrays.
stream(str.substring(1, str.length() - 1).
split(","))
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(s -> s[0].trim(),
s -> s[1].trim()));
System.out.println(map);
}

  • Arrays.stream() to convert string array to stream. 
  • str.substring(1, str.length() - 1) removes curly brackets. 
  • split(","): Split the string to get individual map entries. 
  • s.split("=", 2): Split them by = to get the key and the value and ensure that the array is never larger than two elements. 
  • The collect() method in Stream API collects all objects from a stream object and stores them in the type of collection. 
  • Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()): Accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. 

Example 2: Convert  below String to HashMap 

String str = "[name = rahul:email = rahul@knf.co.in:gender = male]";


Solution 1: Before Java 8 

public static void main(String[] args) {

String str = "[name = rahul:email = rahul@knf.co.in:gender = male]";
//Remove square 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[] args) {

String str = "[name = rahul:email = rahul@knf.co.in:gender = male]";
Map<String, String> map = Arrays.
stream(str.substring(1, str.length() - 1).
split(":"))
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(s -> s[0].trim(),
s -> s[1].trim()));
System.out.println(map);
}
  • Arrays.stream() to convert string array to stream. 
  • str.substring(1, str.length() - 1) removes square brackets. 
  • split(":"): Split the string to get individual map entries. 
  • s.split("=", 2): Split them by = to get the key and the value and ensure that the array is never larger than two elements. 
  • The collect() method in Stream API collects all objects from a stream object and stores them in the type of collection.
  • Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()): Accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. 
More interesting topics... 

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete