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;
}
...
}
Basically the Company class has a List of Person objects, and each Person object can get an Age value.
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?
}
To find median: First, simply sort the array. Then, check if the number of elements present in the array is even or odd. If odd, then simply return the mid value of the array. Else, the median is the average of the two middle values.
The median is the middle value in a set of data. First, organize and order the data from smallest to largest. To find the midpoint value, divide the number of observations by two. If there are an odd number of observations, round that number up, and the value in that position is the median.
median() is a static method of the ObjectUtils class that is used to find the “best guess” middle value among comparables. If there is an even number of total values, the lower of the two middle values will be returned.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With