Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string representing key-value pairs to Map

How can I convert a String into a Map:

Map m = convert("A=4 H=X PO=87"); // What's convert? System.err.println(m.getClass().getSimpleName()+m); 

Expected output:

HashMap{A=4, H=X, PO=87} 
like image 566
PeterMmm Avatar asked Feb 08 '13 08:02

PeterMmm


People also ask

Can we convert string to HashMap in Java?

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.

How do you convert a Map key and value in a string?

Convert a Map to a String Using Java Streams To perform conversion using streams, we first need to create a stream out of the available Map keys. Second, we're mapping each key to a human-readable String.

Can we use string as key in Map?

String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.


1 Answers

There is no need to reinvent the wheel. The Google Guava library provides the Splitter class.

Here's how you can use it along with some test code:

package com.sandbox;  import com.google.common.base.Splitter; import org.junit.Test;  import java.util.Map;  import static org.junit.Assert.assertEquals;  public class SandboxTest {      @Test     public void testQuestionInput() {         Map<String, String> map = splitToMap("A=4 H=X PO=87");         assertEquals("4", map.get("A"));         assertEquals("X", map.get("H"));         assertEquals("87", map.get("PO"));     }      private Map<String, String> splitToMap(String in) {         return Splitter.on(" ").withKeyValueSeparator("=").split(in);     }  } 
like image 93
Daniel Kaplan Avatar answered Sep 22 '22 05:09

Daniel Kaplan