What is Comparator.comparingInt method in Java?
comparingInt is a static method of the Comparator that sorts a list of elements of any type using an integer sort key. The sort key is extracted with the help of the ToIntFunction functional interface, whose implementation is passed as a parameter to the method.
The Comparator interface is defined in the java.util package. To import the Comparator interface, check the following import statement.
import java.util.Comparator;
Syntax
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
Parameters
ToIntFunction<? super T> keyExtractor: Function to extract the sort key.
Return value
The method returns a Comparator.
Code
Let’s have a look at the code:
import java.util.Arrays;import java.util.Comparator;import java.util.List;public class Main1 {static class Packet{int size;public Packet(int size) {this.size = size;}@Overridepublic String toString() {return "Packet{" +"size=" + size +'}';}}public static void main(String[] args) {List<Packet> packetList = Arrays.asList(new Packet(4), new Packet(10), new Packet(2));System.out.println("Before sorting: " + packetList);packetList.sort(Comparator.comparingInt(packet -> packet.size));System.out.println("After sorting: " + packetList);}}
Explanation
- In lines 1-3, we import the relevant packages.
- In line 7, we define a
Packetclass withsizeas the attribute. - In line 23, we create a list of different
Packetobjects with different sizes. - In line 24, we print the list of
Packetobjects created before sorting. - In line 25, we sort the list using the
comparingIntmethod, where we create an implementation of theToIntFunctioninterface that extracts thesizeattribute from thePacketobjects. - In line 26, we print the list of
Packetobjects after sorting.