Search code examples
javaloopsdictionarystringbuilder

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?


Solution

  • You can simply replace value + ", from anonymous\n" with 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?