[英].collect(Collectors.toList()) and Streams on Java Method
I have a collection (as hashmap) of Doctors, into a generic Hospital class. 我有一个医生的集合(作为hashmap),进入一个通用的医院类。
Map<Integer, Doctor> doctors = new HashMap<Integer, Doctor>();
For each doctor I have some information such as in the class code (focus on the patients): 对于每位医生,我都有一些信息,例如课堂代码(专注于患者):
public class Doctor extends Person {
private int id;
private String specialization;
private List<Person> patients = new LinkedList<Person>();
My purpose is to write this function which return busy doctors: doctors that has a number of patients larger than the average. 我的目的是编写这个功能,让繁忙的医生回归:医生的病人数量大于平均水平。
/**
* returns the collection of doctors that has a number of patients larger than the average.
*/
Collection<Doctor> busyDoctors(){
Collection<Doctor> doctorsWithManyPatients =
doctors.values().stream()
.map( doctor -> doctor.getPatients() )
.filter( patientsList -> { return patientsList.size() >= AvgPatientsPerDoctor; })
.collect(Collectors.toList());
return null;
}
I want to use the streams as above to perform this operation. 我想使用上面的流来执行此操作。 The problem is in
collect
method because at that point of usage doctorsWithManyPatients
is of type List<Collection<Person>>
and not Collection<Doctor>
. 问题出在
collect
方法中,因为在使用时, doctorsWithManyPatients
的类型为List<Collection<Person>>
而不是Collection<Doctor>
。 How could I do that? 我怎么能这样做?
Assume that AvgPatientsPerDoctor
is already defined somewhere. 假设已经在某处定义了
AvgPatientsPerDoctor
。
You needn't use map
( Doctor -> List<Person>
), it will be used in the filter
: 你不需要使用
map
( Doctor -> List<Person>
),它将在filter
:
doctors
.values()
.stream()
.filter( d -> d.getPatients().size() >= AvgPatientsPerDoctor)
.collect(Collectors.toList());
For your case, map( doctor -> doctor.getPatients() )
returns Stream<List<Person>>
and you should convert it to Stream<Doctor>
again after filter
ing and before calling the collect
method. 对于您的情况,
map( doctor -> doctor.getPatients() )
返回Stream<List<Person>>
,您应该在filter
之后和调用collect
方法之前将其再次转换为Stream<Doctor>
。
There is a different way that isn't the best one. 有一种不同的方式不是最好的方式。 Keep in mind that it changes the origin collection.
请记住,它会更改原始集合。
doctors.values().removeIf(d -> d.getPatients().size() < AvgPatientsPerDoctor);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.