将HashMap的键和值连接到列表

时间:2016-07-01 05:43:35

标签: java string java-8 java-stream

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

示例:

Map<String,String> tags = new HashMap<>();
tags.put("k1","v1");
tags.put("k2","v2");

然后我想得到字符串

  

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(","));
}

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

1 个答案:

答案 0 :(得分:5)

您不需要中间List。您可以Stream entrySet mapString的每个条目collect String改为return tags.entrySet().stream() .map(e-> String.join(":", e.getKey(), e.getValue())) .sorted() .collect(Collectors.joining(","));

    Update Alias SET RowNum = RN FROM (SELECT *, ROW_NUMBER() 
        OVER (ORDER BY Id) RN FROM YourTable WHERE ISNULL(TIN, '') <> '') Alias