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;
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
ToIntFunction<? super T> keyExtractor
: Function to extract the sort key.The method returns a Comparator
.
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);}}
Packet
class with size
as the attribute.Packet
objects with different sizes.Packet
objects created before sorting.comparingInt
method, where we create an implementation of the ToIntFunction
interface that extracts the size
attribute from the Packet
objects.Packet
objects after sorting.