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}
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.
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With