Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Comparator.comparingInt method in Java?

abhilash

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;
        }

        @Override
        public 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);
    }
}
Implementation of the comparingInt method

Explanation

  • In lines 1-3, we import the relevant packages.
  • In line 7, we define a Packet class with size as the attribute.
  • In line 23, we create a list of different Packet objects with different sizes.
  • In line 24, we print the list of Packet objects created before sorting.
  • In line 25, we sort the list using the comparingInt method, where we create an implementation of the ToIntFunction interface that extracts the size attribute from the Packet objects.
  • In line 26, we print the list of Packet objects after sorting.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring