I have two classes that are structured like this:
public class Company {
private List person;
...
public List getP
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.