What is ObjectUtils.mode in Java?
mode() is a ObjectUtils class that is used to find the most frequently occurring item in a given list of items.
In statistics, the mode is the value that occurs most frequently in a set of data values.
Importing 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>
You can import the ObjectUtils class as follows:
import org.apache.commons.lang3.ObjectUtils;
Syntax
public static <T> T mode(final T... items)
Parameters
final T... items: The list of items.
Return value
This method returns the most frequently occurring item.
Code
import org.apache.commons.lang3.ObjectUtils;import java.util.Arrays;public class Main{public static void main(String[] args) {Integer[] ints = new Integer[]{1,22,2,1,3,42,21,1,2,1,21,1,1};System.out.printf("ObjectUtils.mode(%s) = %s", Arrays.toString(ints), ObjectUtils.mode(ints));}}
In the code above, we define an array of integers. We get the most frequently occurring integer with the help of ObjectUtils.mode().
Output
The output of the code will be as follows:
ObjectUtils.mode([1, 22, 2, 1, 3, 42, 21, 1, 2, 1, 21, 1, 1]) = 1