将表示键值对的字符串转换为Map [英] Convert string representing key-value pairs to Map
本文介绍了将表示键值对的字符串转换为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);
预期输出:
HashMap{A=4, H=X, PO=87}
推荐答案
没有必要重塑轮子。 Google Guava图书馆提供了 Splitter
class 。
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);
}
}
这篇关于将表示键值对的字符串转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文