将 java Map 转换为自定义 key=value 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21166573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:04:33  来源:igfitidea点击:

Convert java Map to custom key=value string

javamapguavaapache-commons

提问by karolkpl

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.

TreeMap<String,String>需要将其转换为类似 URI 的字符串,然后再转换回 Map。我需要设置自定义分隔符。

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 :)

有什么工具(Guava,Apache commons?)可以为我做这件事吗?我知道,我可以编写简单的循环,但我正在寻找单行 :)

For example

例如

key    value
key1   val1
key2   val2

key1_val1|key2_val2

采纳答案by zapl

According to David Tuligyou could do it in guava via

根据David Tulig 的说法,您可以通过在番石榴中做到这一点

 String string = Joiner.on("|").withKeyValueSeparator("_").join(map);

The opposite is also available via

相反的也可以通过

 Map<String, String> map = Splitter.on("|").withKeyValueSeparator("_").split(string);

回答by yurib

its not guava or apache commons, and it is a loop, but aside from instantiating the string builder, it is a one liner:

它不是番石榴或 apache 公共资源,它是一个循环,但除了实例化字符串生成器之外,它还是一个单行:

for (Entry<String,String> entry : myMap.entrySet()) {
    sb.append(entry.getKey() + separator + entry.getValue() + "\n");
}

回答by jokster

Using Java8:

使用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));
}

回答by Timo B?wing

In java 8 and up there is another way without external dependencies: use StringJoiner:

在 java 8 及更高版本中,还有另一种没有外部依赖的方法:使用StringJoiner

    List<String> cities = Arrays.asList("Milan", 
                                        "London", 
                                        "New York", 
                                        "San Francisco");

    String citiesCommaSeparated = String.join(",", cities);

    System.out.println(citiesCommaSeparated);


    //Output: Milan,London,New York,San Francisco

Credits and example go to this URL (https://reversecoding.net/java-8-convert-list-string-comma/)

积分和示例转到此 URL (https://reversecoding.net/java-8-convert-list-string-comma/)