What is ObjectUtils.min in Java?
min() is a ObjectUtils class that is used to get the minimum object from a list of objects. The types/classes of the objects should implement the Comparable interface that defines the way in which the objects are compared.
-
The method returns the lesser object if any objects are non
nulland unequal. -
The method returns the first object if all objects are non
nulland equal. -
The method returns the lesser of the non
nullobjects if any of the comparables arenull. -
The method returns
nullif all the comparables are null.
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 min(final T... values)
Parameters
final T... values: The list of comparable values.
Return value
This method returns the minimum value.
Code
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),null};System.out.printf("ObjectUtils.min(%s) = %s", Arrays.toString(persons), ObjectUtils.min(persons));}}
Output
The output of the code will be as follows:
ObjectUtils.min([Temp{a=3}, Temp{a=5}, Temp{a=8}, Temp{a=10}, null]) = Temp{a=3}
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 person object with the minimum age using the ObjectUtils.min() method.