最优雅的方式来加入Java中的一个String 8 [英] Most elegant way to join a Map to a String in Java 8

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

问题描述

我喜欢番石榴,我会继续使用番石榴。但是,在哪里有意义,我尝试使用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);

哪里结果 a = 1& b = 2& c = 3

问题

在Java 8 (没有任何第三方库)中,最优雅的方式是这样做?

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中的一个String 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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