ohw*_*ppp 13 java java-8 java-stream
我正在尝试通过(映射)进行分组,然后将值列表转换为不同的列表.
我有DistrictDocuments列表:
List<DistrictDocument> docs = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
然后我在它上面流式传输并按城市分组:
Map<String, List<DistrictDocument>> collect = docs.stream()
.collect(Collectors.groupingBy(DistrictDocument::getCity));
Run Code Online (Sandbox Code Playgroud)
我还有一个方法,它采用了DistrictDocument并从中创建了Slugable:
private Fizz createFizz(DistrictDocument doc) {
return new Fizz().name(doc.getName()).fizz(doc.getFizz());
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将该方法放入我的流中,所以我得到了Map<String, List<Fizz>>?我尝试将第二个参数添加到groupingBy但是找不到合适的方法并且总是遇到编译错误.
编辑:如果我的createFizz返回List<Fizz>怎么办?是否可以选择在Collectors.mapping中平展此列表,因为我仍然想要Map<String, List<Fizz>>而不是Map<String, List<List<Fizz>>>
Era*_*ran 22
您需要将Collectors.mapping()收集器链接到Collectors.groupingBy()收集器:
Map<String, List<Fizz>> collect =
docs.stream()
.collect(Collectors.groupingBy(DistrictDocument::getCity,
Collectors.mapping(d->createFizz(d),Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
如果createFizz(d)要返回a List<Fizz,你可以使用Java 9来展平它Collectors.flatMapping:
Map<String, List<Fizz>> collect =
docs.stream()
.collect(Collectors.groupingBy(DistrictDocument::getCity,
Collectors.flatMapping(d->createFizz(d).stream(),Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
如果你不能使用Java 9,也许使用Collectors.toMap将有助于:
Map<String, List<Fizz>> collect =
docs.stream()
.collect(Collectors.toMap(DistrictDocument::getCity,
d->createFizz(d),
(l1,l2)->{l1.addAll(l2);return l1;}));
Run Code Online (Sandbox Code Playgroud)
Fab*_*ian 10
如果您想进行双重嵌套分组:
假设您有一个EducationData包含学校名称、教师姓名和学生姓名的对象集合。但您想要一个如下所示的嵌套地图:
class EducationData {
String school;
String teacher;
String student;
// getters setters ...
}
Run Code Online (Sandbox Code Playgroud)
Map<String, Map<String, List<String>>> desiredMapOfMpas ...
// which would look like this :
"East High School" : {
"Ms. Jackson" : ["Derek Shepherd", "Meredith Grey", ...],
"Mr. Teresa" : ["Eleanor Shellstrop", "Jason Mendoza", ...],
....
}
Run Code Online (Sandbox Code Playgroud)
import static java.util.stream.Collectors.*;
public doubleNestedGroup(List<EducationData> educations) {
Map<String, Map<String, List<String>>> nestedMap = educations.stream()
.collect(
groupingBy(
EducationData::getSchool,
groupingBy(
EducationData::getTeacher,
mapping(
EducationData::getStudent,
toList()
)
)
)
);
}
Run Code Online (Sandbox Code Playgroud)