将HashMap的键和值连接到列表

fre*_*ee斩 4 java string java-8 java-stream

我想将一个HashMap键和值连接到一个带有':'的字符串,并将它们转换为一个列表.

例:

Map<String,String> tags = new HashMap<>();
tags.put("k1","v1");
tags.put("k2","v2");
Run Code Online (Sandbox Code Playgroud)

然后我想得到字符串

K1:V1,K2:V2

我的代码是:

private String transe(Map<String, String> tags) {
    if (tags == null || tags.isEmpty()) {
        return DEFAULT_STATUS_GROUP;
    }
    List<String> tagKVList = new ArrayList<>();
    tags.forEach((key, value) -> tagKVList.add(String.join(":", key, value)));
    tagKVList.sort((tag1, tag2) -> tag1.compareTo(tag2));
    return tagKVList.stream().collect(Collectors.joining(","));
}
Run Code Online (Sandbox Code Playgroud)

如何删除局部变量tagKVList并使代码更清晰?

Era*_*ran 5

你不需要中间体List.你可以StreamentrySet,map每个条目的Stringcollect一个单一的String,你已经这样做:

return tags.entrySet().stream()
                      .map(e-> String.join(":", e.getKey(), e.getValue()))
                      .sorted()
                      .collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)

  • 好的旧的`e.getKey()+":"+ e.getValue()`也可以代替`String.join(":",e.getKey(),e.​​getValue())`...哦,你忘记了`sorted()`步骤. (3认同)