I have TreeMap<String,String>
which I need to convert to URI-like string and then back to Map.
I need to set custom delimiters.
Is there any tool (Guava, Apache commons?) that can do it for me? I know, I can write simple loops, but I'm looking for one-liner :)
For example
key value
key1 val1
key2 val2
key1_val1|key2_val2
Using toString() method The string representation of a map consists of a list of key-value pairs enclosed within curly braces, where the adjacent pairs are delimited by a comma followed by a single space and each key-value pair is separated by the equals sign ( = ). i.e., {K1=V1, K2=V2, ..., Kn=Vn} .
HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
According to David Tulig you could do it in guava via
String string = Joiner.on("|").withKeyValueSeparator("_").join(map);
The opposite is also available via
Map<String, String> map = Splitter.on("|").withKeyValueSeparator("_").split(string);
Using 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));
}
its not guava or apache commons, and it is a loop, but aside from instantiating the string builder, it is a one liner:
for (Entry<String,String> entry : myMap.entrySet()) {
sb.append(entry.getKey() + separator + entry.getValue() + "\n");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With