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... 

Comments

Popular posts from this blog

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

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

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

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example