.collect(Collectors.toList()) 和 Streams on Java 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37419278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:29:07  来源:igfitidea点击:

.collect(Collectors.toList()) and Streams on Java Method

javajava-8java-stream

提问by Giuseppe Canto

I have a collection (as hashmap) of Doctors, into a generic Hospital class.

我有一个医生的集合(作为哈希图),放到一个通用的医院类中。

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 collectmethod because at that point of usage doctorsWithManyPatientsis of type List<Collection<Person>>and not Collection<Doctor>. How could I do that?

我想使用上述流来执行此操作。问题出在collect方法上,因为在那个时候使用的doctorsWithManyPatients是 typeList<Collection<Person>>而不是Collection<Doctor>。我怎么能那样做?

Assume that AvgPatientsPerDoctoris already defined somewhere.

假设AvgPatientsPerDoctor已经在某处定义了。

回答by Andrew Tobilko

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 filtering and before calling the collectmethod.

对于您的情况,map( doctor -> doctor.getPatients() )返回Stream<List<Person>>并且您应该Stream<Doctor>filtering之后和调用该collect方法之前再次将其转换为。



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);