Return to site

JAVA CERTIFICATION QUESTION: Lambda and Min

· java

Given:

import java.util.Optional;
import java.util.stream.Stream;

public class OcpW48 {
    public static void main( String[] args ) {
        Champion jeanne = new Champion( 2019, "Jeanne" );
        Champion ian = new Champion( 2005, "Ian" );
        Champion geertjan = new Champion( 2020, "Geertjan" );
        Optional champion = Stream.of( jeanne, ian, geertjan )
                                  .min( ( c1, c2 ) -> c1.year + c2.year );
        System.out.println( (( Champion ) champion.get()).name );
    }
}

class Champion {
    int    year;
    String name;

    Champion( int year, String name ) {
        this.year = year;
        this.name = name;
    }
}

What is printed?

  • Jeanne
  • Ian
  • Geertjan
  • An exception is thrown
  • Compilation fails

#java #certificationquestion #ocp

The Stream.min finds the minimum element of the stream according to the provided comparator.

A comparator compares its two arguments for order, returning a negative integer, zero, or a positive integer as the first argument is less than, equal to or greater than the second.

Here, the comparator always returns a positive number. This means an element is always deemed greater than the following one.

So, the last Champion instance is considered the minimum element, and "Geertjan" get printed out.