free斩
free斩

Reputation: 441

Connect a HashMap's key and value to a list

I want to connect a HashMap's key and value to a string with ':', and transform them to a list.

Example:

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

then I want to get the string

k1:v1,k2:v2

my code is:

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

How can I remove the local variable tagKVList and make the code clearer?

Upvotes: 4

Views: 115

Answers (1)

Eran
Eran

Reputation: 393801

You don't need the intermediate List. You can Stream the entrySet, map each entry to a String and collect to a single String as you already do :

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

Upvotes: 5

Related Questions