PeterMmm PeterMmm - 1 year ago 92
Java Question

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?

Expected output:

HashMap{A=4, H=X, PO=87}

Answer Source

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 org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class SandboxTest {

    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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download