使用Java 8从对象列表中查找中值 [英] Finding the median value from a List of objects using Java 8

查看:753
本文介绍了使用Java 8从对象列表中查找中值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个结构如下的类:

I have two classes that are structured like this:

public class Company {
     private List<Person> person;
     ...
     public List<Person> getPerson() {
          return person;
     }
     ...
}

public class Person {
     private Double age;
     ...
     public Double getAge() {
          return age;
     }
     ...
}

基本上公司类有一个Person对象列表,每个Person对象都可以得到一个Age值。

Basically the Company class has a List of Person objects, and each Person object can get an Age value.

如果我得到Person对象的列表,是否有一个很好的方法来使用Java 8找到所有Person对象中的Age值的中位数(Stream不支持中位数但是还有其他东西)?

If I get the List of the Person objects, is there a good way to use Java 8 to find the median Age value among all the Person objects (Stream doesn't support median but is there anything else)?

Double medianAge;
if(!company.getPerson().isEmpty) {
     medianAge = company.getPerson() //How to do this in Java 8?
}


推荐答案

你可以用

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;

而不是。

这篇关于使用Java 8从对象列表中查找中值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆