Java 8中将Map连接到String的最佳方法

ldioqlga  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(200)

我喜欢Guava,我会继续大量使用Guava,但是,如果它有意义,我会尝试使用 * Java8 * 中的“新东西”。

“问题”

假设我想在String中连接url属性,在 Guava 中我会这样做:

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

其中resulta=1&b=2&c=3

问题

Java 8 中(没有任何第三方库),最优雅的方法是什么?

oxalkeyp

oxalkeyp1#

您可以获取map的条目集流,然后将每个条目Map到所需的字符串表示,使用Collectors.joining(CharSequence delimiter)将它们连接到单个字符串中。

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

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

但是由于条目的toString()已经以key=value输出了它的内容,所以可以直接调用它的toString方法:

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

ltqd579y2#

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().
                // you can improve the performance by avoiding "+"
                // "map(entrySet -> "%s:%s".formatted(entrySet.getKey(), entrySet.getValue())."
                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

相关问题