What is ObjectUtils.median() in Java?
Overview
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
Comparableinterface that defines the way in which the objects are compared.
How to import 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-langpackage, refer to the Maven Repository.
You can import the ObjectUtils class as follows:
import org.apache.commons.lang3.ObjectUtils;
Syntax
public static <T extends Comparable<? super T>> T median(final T... items)
Parameters
final T... values: The list of comparable values.
Return value
This method returns the middle value of the provided list.
Code
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));}}
Explanation
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.
Output
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}