ArrayList转换成逗号分隔的字符串



我有一个包含

的arrayListList List = new ArrayList<>()

aList{
String name,
String id
}

我有一个包含键和值作为字符串的映射String>Map<字符串;map>();

从arrayList- list中,我想将Name-Id合并为一个包含逗号分隔字符串的字段,然后将其添加到map中例:

name-id = John-1, Jack-2 (And no comma at the end)

在Map中我想添加如下内容

map.put("Name-id", name-id.toString());

Thanks in advance

看起来您需要在AList类中重写方法toString,然后使用Collectors.groupingBy+Collectors.mappingList<AList>转换为映射:

class AList {
String name, id;
@Override
public String toString() {
return String.join("-", name, id);
}
}
List<AList> list = buildList(); // build a list of AList objects
Map<String, List<String>> mapEx = list
.stream()
.collect(Collectors.groupingBy(
x -> "Name-id",
Collectors.mapping(AList::toString, Collectors.toList())
));
// get comma-separated string
Map<String, String> mapEx2 = list
.stream()
.collect(Collectors.groupingBy(
x -> "Name-id",
Collectors.mapping(AList::toString, Collectors.joining(", "))
));

最新更新