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

你离开我真会死。 提交于 2019-12-01 17:25:23

You may use

List<Person> 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<Person> 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.

Obligatory Guava way.

import java.util.List;
import java.util.stream.Collectors;

import com.google.common.math.Quantiles;

...

List<Person> people = company.getPerson();
List<Double> ages = people.stream().map(Person::getAge).collect(Collectors.toList());
double median = Quantiles.median().compute(ages);

Though as of Guava 28.1 Quantiles is still annotated as @Beta.

Here's a simplified version of @Holger's answer that also works for IntStream and LongStream, and avoids NoSuchElementException in the case of an empty stream:

int size = someList.size();

//replace 'XXX' with 'Int', 'Long', or 'Double' as desired
return someList.stream().mapToXXX(...).sorted()
    .skip((size-1)/2).limit(2-size%2).average().orElse(Double.NaN);

This will return NaN if the list is empty rather than throwing NoSuchElementException. If you'd prefer to throw a NoSuchElementException instead, simply replace .orElse(Double.NaN) with .getAsDouble().

You can use lambda expression reduction to get the median of list. Something like this

Integer median = Person .stream() .map(Person::getAge) .filter(n -> n.length()/2);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!