Finding the median value from a List of objects using Java 8

后端 未结 4 1662
遇见更好的自我
遇见更好的自我 2020-12-11 04:28

I have two classes that are structured like this:

public class Company {
     private List person;
     ...
     public List getP         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 05:01

    You may use

    List list = company.getPerson();
    DoubleStream sortedAges = list.stream().mapToDouble(Person::getAge).sorted();
    double median = list.size()%2 == 0?
        sortedAges.skip(list.size()/2-1).limit(2).average().getAsDouble():        
        sortedAges.skip(list.size()/2).findFirst().getAsDouble();
    

    The advantage of this approach is that it doesn’t modify the list and hence also doesn’t rely on its mutability. However, it’s not necessarily the simplest solution.

    If you have the option of modifying the list, you can use

    List list = company.getPerson();
    list.sort(Comparator.comparingDouble(Person::getAge));
    double median = list.get(list.size()/2).getAge();
    if(list.size()%2 == 0) median = (median + list.get(list.size()/2-1).getAge()) / 2;
    

    instead.

提交回复
热议问题