在 Java 8 中将 Map 连接到 String 的最优雅方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32943179/
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-11-02 20:59:30  来源:igfitidea点击:

Most elegant way to join a Map to a String in Java 8

javadictionaryjava-8java-stream

提问by tomaj

I love Guava, and I'll continue to use Guava a lot. But, where it makes sense, I try to use the "new stuff" in Java 8instead.

我喜欢Guava,我会继续大量使用 Guava 。但是,在有意义的地方,我尝试使用Java 8 中的“新东西” 。

"Problem"

“问题”

Lets say I want to join url attributes in a String. In GuavaI would do it like this:

假设我想将 url 属性加入String. 在番石榴中,我会这样做:

Map<String, String> attributes = new HashMap<>();
attributes.put("a", "1");
attributes.put("b", "2");
attributes.put("c", "3");

// Guava way
String result = Joiner.on("&").withKeyValueSeparator("=").join(attributes);

Where the resultis a=1&b=2&c=3.

resulta=1&b=2&c=3

Question

问题

What is the most elegant way to do this in Java 8(without any 3rd party libraries)?

Java 8 中执行此操作的最优雅方法是什么(没有任何 3rd 方库)?

回答by Alexis C.

You can grab the stream of the map's entry set, then map each entry to the string representation you want, joining them in a single string using Collectors.joining(CharSequence delimiter).

您可以获取地图条目集的流,然后将每个条目映射到您想要的字符串表示形式,并使用Collectors.joining(CharSequence delimiter).

import static java.util.stream.Collectors.joining;

String s = attributes.entrySet()
                     .stream()
                     .map(e -> e.getKey()+"="+e.getValue())
                     .collect(joining("&"));

But since the entry's toString()already output its content in the format key=value, you can call its toStringmethod directly:

但是由于条目toString()已经以 format 格式输出其内容key=value,您可以toString直接调用其方法:

String s = attributes.entrySet()
                     .stream()
                     .map(Object::toString)
                     .collect(joining("&"));

回答by Arpan Saini

 public static void main(String[] args) {


        HashMap<String,Integer> newPhoneBook = new HashMap(){{
            putIfAbsent("Arpan",80186787);
            putIfAbsent("Sanjay",80186788);
            putIfAbsent("Kiran",80186789);
            putIfAbsent("Pranjay",80186790);
            putIfAbsent("Jaiparkash",80186791);
            putIfAbsent("Maya",80186792);
            putIfAbsent("Rythem",80186793);
            putIfAbsent("Preeti",80186794);

        }};


        /**Compining Key and Value pairs and then separate each pair by some delimiter and the add prefix and Suffix*/
        String keyValueCombinedString = newPhoneBook.entrySet().stream().
                map(entrySet -> entrySet.getKey() + ":"+ entrySet.getValue()).
                collect(Collectors.joining("," , "[","]"));
        System.out.println(keyValueCombinedString);

        /**
         *  OUTPUT : [Kiran:80186789,Arpan:80186787,Pranjay:80186790,Jaiparkash:80186791,Maya:80186792,Sanjay:80186788,Preeti:80186794,Rythem:80186793]
         *
         * */


        String keyValueCombinedString1 = newPhoneBook.entrySet().stream().
                map(Objects::toString).
                collect(Collectors.joining("," , "[","]"));
        System.out.println(keyValueCombinedString1);

        /**
         * Objects::toString method concate key and value pairs by =
         * OUTPUT : [Kiran=80186789,Arpan=80186787,Pranjay=80186790,Jaiparkash=80186791,Maya=80186792,Sanjay=80186788,Preeti=80186794,Rythem=80186793]
         * */

    }

> Blockquote