median()
is a 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.
The types or classes of the objects should implement the
Comparable
interface that defines the way in which the objects are compared.
ObjectUtils
The definition of ObjectUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the ObjectUtils
class as follows:
import org.apache.commons.lang3.ObjectUtils;
public static <T extends Comparable<? super T>> T median(final T... items)
final T... values
: The list of comparable values.This method returns the middle value of the provided list.
The code below shows how to use the median()
method.
import org.apache.commons.lang3.ObjectUtils;import java.util.Arrays;public class Main{static class Person implements Comparable<Person>{private int age;public Person(int age) {this.age = age;}@Overridepublic int compareTo(Person p) {return this.age - p.age;}@Overridepublic String toString() {return "Person{" +"age=" + age +'}';}}public static void main(String[] args) {Person[] persons = new Person[]{new Person(3),new Person(5),new Person(8),new Person(10)};System.out.printf("ObjectUtils.median(%s) = %s", Arrays.toString(persons), ObjectUtils.median(persons));}}
In the code above, we define a class, Person
, that has age
as its attribute. The class implements the Comparable
interface and the compareTo()
method is overridden with custom logic of comparison.
In line 28, an array of Person
class objects is defined with different values for age.
In line 35, we get the middle object defined as per the logic defined in the compareTo()
method using the ObjectUtils.median()
method.
The output of the code will be as follows:
ObjectUtils.median([Person{age=3}, Person{age=5}, Person{age=8}, Person{age=10}]) = Person{age=5}