我是Java新手。我有一个问题,我需要实现一种将字符串解码为相应的decode(String)
的{{1}}方法。在作业中,要求是这样的,
Map
Sample Input: one=1&two=2
Should return a Map containing {"one": "1", "two": "2"}
我的代码是根据需要提供输出,但是我已经使用Map<String, String> map = new HashMap<>();
map.put("One", "1");
map.put("Two", "2");
map.put("", "");
map.put("Key", "");
map.put("", "Value");
Set<String> keys = map.keySet();
for(String key : keys) {
System.out.print("\"" + key + "\"" + ":" + "\"" + map.get(key) + "\"");
}
接口在main方法中实现了这一点,而我需要编写以Map<K, V>
作为参数并解码为Map的代码
谢谢
答案 0 :(得分:1)
一种解决方案可能是:
public Map<String, String> parseMap(String mapString) {
if (mapString == null || mapString.isEmpty()) {
return Collections.emptyMap();
}
return Arrays.stream(mapString.split("&"))
.map(this::splitParam)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
}
public AbstractMap.SimpleEntry<String, String> splitParam(String it) {
final int idx = it.indexOf("=");
final String key = it.substring(0, idx);
final String value = it.substring(idx + 1);
return new AbstractMap.SimpleEntry<>(key, value);
}
用法
String inputString = "one=1&two=2";
Map<String, String> map = parseMap(inputString);
//your code to print the map again
Set<String> keys = map.keySet();
for(String key : keys) {
System.out.print("\"" + key + "\"" + ":" + "\"" + map.get(key) + "\"");
}
答案 1 :(得分:1)
在编辑器中尝试一下,只需4行:)
String input = "one=1&two=2";
String[] kvs = input.split("&");
Map<String, String> hashMap = Stream.of(kvs)
.collect(Collectors.toMap(item -> item.split("=")[0],
item -> item.split("=")[1]));
hashMap.forEach((k, v) -> System.out.println(k + ":" + v));