将 java Map 转换为自定义键=值字符串
2022-09-03 03:50:00
我有我需要转换为类似URI的字符串,然后返回到Map。我需要设置自定义分隔符。TreeMap<String,String>
有什么工具(番石榴,Apache commons?)可以为我做到这一点吗?我知道,我可以写简单的循环,但我正在寻找单行:)
例如
key value
key1 val1
key2 val2
key1_val1|key2_val2
我有我需要转换为类似URI的字符串,然后返回到Map。我需要设置自定义分隔符。TreeMap<String,String>
有什么工具(番石榴,Apache commons?)可以为我做到这一点吗?我知道,我可以写简单的循环,但我正在寻找单行:)
例如
key value
key1 val1
key2 val2
key1_val1|key2_val2
根据大卫·图利格的说法,你可以通过番石榴来做
String string = Joiner.on("|").withKeyValueSeparator("_").join(map);
反之亦然,也可以通过以下方式获得
Map<String, String> map = Splitter.on("|").withKeyValueSeparator("_").split(string);
使用 Java8:
private static Map<String, String> prepareMap() {
Map<String, String> map = new LinkedHashMap<>();
map.put("key1", "val1");
map.put("key2", "val2");
return map;
}
@Test
public void toStr() {
assertEquals("key1_val1|key2_val2", prepareMap().entrySet().stream()
.map(e -> e.getKey() + "_" + e.getValue())
.collect(Collectors.joining("|")));
}
@Test
public void toStrFunction() {
assertEquals("key1_val1|key2_val2", joiner("|", "_").apply(prepareMap()));
}
private static Function<Map<String, String>, String> joiner(String entrySeparator, String valueSeparator) {
return m -> m.entrySet().stream()
.map(e -> e.getKey() + valueSeparator + e.getValue())
.collect(Collectors.joining(entrySeparator));
}
@Test
public void toMap() {
assertEquals("{key1=val1, key2=val2}", Stream.of("key1_val1|key2_val2".split("\\|"))
.map(e -> e.split("_", 2))
.collect(Collectors.toMap(e -> e[0], e -> e.length > 1 ? e[1] : null)).toString());
}
@Test
public void toMapFunction() {
assertEquals("{key1=val1, key2=val2}", splitter("\\|", "_").apply("key1_val1|key2_val2").toString());
}
private static Function<String, Map<String, String>> splitter(String entrySeparator, String valueSeparator) {
return s -> Stream.of(s.split(entrySeparator))
.map(e -> e.split(valueSeparator, 2))
.collect(Collectors.toMap(e -> e[0], e -> e.length > 1 ? e[1] : null));
}