简体   繁体   中英

How to use StringBuilder with Map

I have a following map

Map<String, String> map = new HashMap<>();

And collection of dto

 List<MyDto> dtoCollection = new ArrayList<>();
 
 class MyDto {
    String type;
    String name;
 }

for(MyDto dto : dtoCollection) {
   map.compute(dto.getType(), (key,value) -> value + ", from anonymous\n"());
}

And the question is how to replace Map<String, String> to Map<String, StrinBuilder> and make append inside the loop?

You can simply replace value + ", from anonymous\n" with value == null? new StringBuilder(dto.getName()): value.append(", from anonymous\n")) value == null? new StringBuilder(dto.getName()): value.append(", from anonymous\n")) .

Illustration:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class MyDto {
    String type;
    String name;

    public MyDto(String type, String name) {
        this.type = type;
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Map<String, StringBuilder> map = new HashMap<>();
        List<MyDto> dtoCollection = new ArrayList<>();
        for (MyDto dto : dtoCollection) {
            map.compute(dto.getType(), (key, value) -> value == null ? new StringBuilder(dto.getName())
                    : value.append(", from anonymous\n"));
        }
    }
}

Am I missing something?

Such methods as Map::merge or collection to map would require creation of extra StringBuilder instances which should be concatenated then:

map.merge(
    dto.getType(), 
    new StringBuilder(dto.getName()).append(" from anonymous\n"), // redundant StringBuilder
    (v1, v2) -> v1.append(v2) // merging multiple string builders
);

It is possible to use computeIfAbsent to create only one instance of StringBuilder when it's missing in the map and after that call append to the already existing value:

Map<String, StringBuilder> map = new HashMap<>();
List<MyDto> dtoCollection = Arrays.asList(
    new MyDto("type1", "aaa"), new MyDto("type2", "bbb"), 
    new MyDto("type3", "ccc"), new MyDto("type1", "aa2"));
for (MyDto dto : dtoCollection) {
    map.computeIfAbsent(dto.getType(), (key) -> new StringBuilder()) // create StringBuilder if needed
       .append(dto.getName()).append(" from anonymous\n");
}
System.out.println(map);

Output:

{type3=ccc from anonymous
, type2=bbb from anonymous
, type1=aaa from anonymous
aa2 from anonymous
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM