我是 Java 新手。我有一个问题,我需要实现 decode(String)
将 String 解码为相应的 Map
的方法。作业中,要求是这样的,
- 允许使用空键和值,但必须存在等号(例如“=value”、“key=”)。
- 如果键或值为空,则应返回空字符串。
- 如果给定的 String 为空,则应返回一个空的 Map。
- 如果给定的 String 为 null,则应返回 null。
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) + "\"");
}
我的代码根据需要给出输出,但我已经在主方法中使用 Map<K, V>
实现了这一点接口(interface),而我需要编写需要 String
的代码作为参数并解码为 Map。
谢谢
最佳答案
一种解决方案可能是:
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) + "\"");
}
关于java - 如何将String解码为对应的Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56663828/