How do I use Collectors.minBy() method?

The Collectors.minBy() method in Java 8 is used to find the minimum element from a stream of elements based on a certain comparator. It returns an Optional describing the minimum element of the stream, or an empty Optional if the stream is empty.

Here’s an example of how to use Collectors.minBy(). Assume we have a list of integers, and we want to find the smallest element.

package org.kodejava.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class CollectorsMinBy {
    public static void main(String... args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        Optional<Integer> min = numbers.stream()
                .collect(Collectors.minBy(Integer::compare));

        min.ifPresent(System.out::println);
    }
}

In this code:

  • We have a list of integers.
  • We create a Stream from the list and collect the stream into an Optional that might hold the minimum value via the Collectors.minBy(Integer::compare) collector.
  • Integer::compare is a method reference that is used to instruct Collectors.minBy() on how to compare the integers.
  • min.ifPresent(System.out::println) checks if the Optional has a value. If it does, the value is passed to the System.out::println method and printed to the console.

When run, this program prints the smallest number in our list, which is “1”.

Note that if the list is empty, min will hold an empty Optional, and min.ifPresent(System.out::println) will not print anything.

Here’s another example of how you can use the Collectors.minBy() method to find the object containing the minimum value for a certain property. Let’s assume we have a Person class and a list of Person objects, and we want to find which Person has the smallest age.

package org.kodejava.stream;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class CollectorsMinByObjectProperty {
    public static void main(String... args) {
        List<Person> people = Arrays.asList(
                new Person("Rosa", 21),
                new Person("Bob", 25),
                new Person("Alice", 18),
                new Person("John", 22));

        Optional<Person> youngestPerson = people.stream()
                .collect(Collectors.minBy(Comparator.comparingInt(Person::getAge)));

        youngestPerson.ifPresent(System.out::println);
    }

    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        @Override
        public String toString() {
            return "Person{" +
                   "name='" + name + '\'' +
                   ", age=" + age +
                   '}';
        }
    }
}

Output:

Person{name='Alice', age=18}

In this code:

  • The Person class has two fields, name and age, and a getter for the age field.
  • We have a list of Person objects.
  • We create a Stream from the list and then use Collectors.minBy() to find the Person with the smallest age. To do this, we use Comparator.comparingInt(Person::getAge), which compares the Person objects based on their age.
  • Collectors.minBy() returns an Optional that might hold the Person with the smallest age.
  • If such a Person exists, we print that Person using System.out::println.

This program prints: Person{name='Alice', age=18}, as Alice is the person with the smallest age.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.