[英]How to use StringBuilder with Map
I have a following map我有以下 map
Map<String, String> map = new HashMap<>();
And collection of dto并收集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?问题是如何将 Map<String, String> 替换为 Map<String, StrinBuilder> 并使 append 在循环内?
You can simply replace value + ", from anonymous\n"
with value == null? new StringBuilder(dto.getName()): value.append(", from anonymous\n"))
您可以简单地将
value + ", from anonymous\n"
替换为value == null? new StringBuilder(dto.getName()): value.append(", from anonymous\n"))
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
或收集到 map 之类的方法需要创建额外的 StringBuilder 实例,然后将这些实例连接起来:
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 中缺少
StringBuilder
时,可以使用computeIfAbsent
仅创建一个实例,然后将append
调用到现有值:
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: Output:
{type3=ccc from anonymous
, type2=bbb from anonymous
, type1=aaa from anonymous
aa2 from anonymous
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.