在 Java 8 中将 Map 连接到 String 的最优雅方式 [英] Most elegant way to join a Map to a String in Java 8

查看:54
本文介绍了在 Java 8 中将 Map 连接到 String 的最优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 8 instead.

问题"

假设我想在 String 中加入 url 属性.在 Guava 中,我会这样做:

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

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 中最优雅的方法是什么(没有任何 3rd 方库)?

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

推荐答案

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

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

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

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

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

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

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

这篇关于在 Java 8 中将 Map 连接到 String 的最优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆