Finding min and max of Stream using min(), max() functions in Java 8

Java 8 Stream class provides methods min() and max() for finding minimum and maximum values in a stream.

Java 8 also added a static method comparing() to the Comparator class that lets us build a comparator using a sort key.

Lets see some examples of Stream min() and max() functions with the Comparator.comparing() method.
 

min() function example : Finding youngest person

package com.topjavatutorial.java8examples;

public class Person {
  private String name;
  private int age;

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

  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }

  public String toString() {
    return "Name : " + getName() + ", Age : " + getAge();
  }
}

List<Person> persons = Arrays.asList(new Person("Alex", 23),
    new Person("Bob", 13), new Person("Chris", 43));
persons.stream().min(Comparator.comparing(Person::getAge))
    .ifPresent(youngest -> System.out.println("Youngest Person [" + youngest + "]"));

Output :

Youngest Person [Name : Bob, Age : 13]

 

max() function example : Finding oldest person

persons.stream().max(Comparator.comparing(Person::getAge))
        .ifPresent(oldest -> System.out.println("Oldest Person [" + oldest + "]"));

Output :

Oldest Person [Name : Chris, Age : 43]
 

Finding min() and max() of IntStream

int[] numbers = {23,12,45,2,67};
int minimum = IntStream.of(numbers).min().getAsInt();
System.out.println("Min = " + minimum);
int maximum = IntStream.of(numbers).max().getAsInt();
System.out.println("Max = " + maximum);

Output :

Min = 2
Max = 67

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags