【发布时间】:2021-07-28 05:17:46
【问题描述】:
Object2 类具有标准 getter,并具有 String 字段 folder、file 和 version。
它被命名为SourceInfo
List<SourceInfo> source 包含上述三个字段。
我的目标是从List<SourceInfo> 创建一个List<Info>。
新List的类是Info,如下图。
public class Info {
private final String folder;
private final Map<String, Set<String>> file;
public static Builder builder() {
return new Builder();
}
public static Builder builder(Info info) {
return new Builder(info);
}
private Info(Builder builder) {
this.folder = builder.folder;
this.file = builder.file;
}
public String getFolder() {
return folder;
}
public Map<String, Set<String>> getFile() {
return file;
}
// autogenerated toString, hashCode, and equals
public static class Builder {
private String folder;
private Map<String, Set<String>> file;
private Builder() {}
private Builder(Info info) {
this.folder = info.folder;
this.file = info.file;
}
public Builder with(Consumer<Builder> consumer) {
consumer.accept(this);
return this;
}
public Builder withFolder(String folder) {
this.folder = folder;
return this;
}
public Builder withFile(Map<String, Set<String>> file) {
this.file = file;
return this;
}
public Info build() {
return new Info(this);
}
}
到目前为止,我尝试的是在构建器模式中创建一个集合。
List<SourceInfo> source;
// error: gc overhead limit exceeded
List<Info> infoList = source.stream()
.map(e -> Info.builder()
.withFolder(e.getFolder())
.withFile(source.stream()
.collect(Collectors.groupingBy(SourceInfo::getKey,
Collectors.mapping(SourceInfo::getVersion, Collectors.toSet()))))
.build())
.collect(Collectors.toList());
Map<String, Set<String>> map = source.stream()
.collect(Collectors
.groupingBy(SourceInfo::getKey,
Collectors.mapping(SourceInfo::getVersion, Collectors.toSet())));
List<Info> info = source.stream()
.map(e -> Info.builder()
.withFolder(e.getFolder())
.withFile(map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue)))
.build())
.collect(Collectors.toList());
所需的输出。以下语法可能已关闭。
// [String, Map<String, Set<String>>]
Info [folder, [key=file [value=version]]]
...
我是 Java 新手,不胜感激。
我想了解如何使用 java8 和 for 循环来做到这一点。
谢谢。
【问题讨论】:
标签: java list for-loop set java-stream