【问题标题】:Most elegant way to join a Map to a String in Java 8在 Java 8 中将 Map 连接到 String 的最优雅方式
【发布时间】:2016-01-01 18:57:01
【问题描述】:

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

“问题”

假设我想在 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&amp;b=2&amp;c=3

问题

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

【问题讨论】:

  • “仅使用 Java 8”是相当模糊的,因为您在 Java 7 中可以做的任何事情也可以在 Java 8 中完成。
  • 意思是使用 Java 8,没有任何库。如果进行此练习,图书馆将无法达到目的。 Java 8 还附带了一些不错的 api,以及 Java 7 所没有的语法更改。这为一些优雅的编程打开了大门。
  • 附注:如果您希望创建一个 URL 查询字符串,那么您的做法是错误的,因为您需要转义可能出现在键名或值中的特殊字符。
  • 好点@TagirValeev。

标签: java dictionary java-8 java-stream


【解决方案1】:

您可以获取映射条目集的流,然后将每个条目映射到您想要的字符串表示形式,使用 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("&"));

【讨论】:

  • 请注意,虽然 HashMap 条目实际上以 key=value 格式打印,但从未指定过,因此依赖此事实是一种不好的做法。
  • 这就是我提供第一个替代方案的原因。
【解决方案2】:
 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2020-03-17
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多