Monday, November 8, 2021

Java Stream - max() With Examples

In Java Stream API there is a max() method that is used to get the maximum element of this stream according to the provided Comparator. In this post we’ll see some examples of the max() method.

Syntax of the Stream.max() method

max is a terminal operation and its syntax is as given below-

Optional<T> max(Comparator<? super T> comparator)

Here comparator is an implementation of Comparator to compare elements of this stream.

Method returns an Optional containing the maximum element of the stream or an empty Optional if the stream is empty.

max() method is considered a reduction operation as it takes a sequence of input elements and combines them into a single summary result.

max() method Java examples

1. Finding max value from a stream of numbers.

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

public class StreamMax {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(6, 8, 13, 2, 58, 22, 76, 9, 11, 3);
      Optional<Integer> max = numList.stream().max(Integer::compare);
      if(max.isPresent()){
        System.out.println("Maximum element: " + max.get());
      }
  }
}

Output

Maximum element: 76

2. In the following example custom comparator is passed as an argument to the max() method.

public class StreamMax {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(6, 8, 13, 2, 58, 22, 76, 9, 11, 3);
      Optional<Integer> max = numList.stream().max(new MyComparator());
      if(max.isPresent()){
        System.out.println("Maximum element: " + max.get());
      }
  }
}

class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer o1, Integer o2) {
    // TODO Auto-generated method stub
    return o1.compareTo(o2);
  }
}

Output

Maximum element: 76

Here MyComparator is an implementation of the Comparator where compare method compares two integers. An instance of MyComparator is passed as argument to the max() method.

3. Using max() method with custom object. In the example objects of Employee class are used and the objective is to find max salary using the max() method of the Java Stream API.

Employee class used is as given here.

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
}

Here max() is used in conjunction with mapToInt() to get the salary part of the employee object which is then passed to the max() to get the max salary.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;

public class StreamMax {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Rani", 'F', 10000),
                 new Employee("E005", 32, "Anuj", 'M', 12000));  
     OptionalInt maxEmpSal = empList.stream()
                 .mapToInt(Employee::getSalary)
                 .max();
      if(maxEmpSal.isPresent()){
        System.out.println("Maximum salary: " + maxEmpSal.getAsInt());
      }
  }
}

Output

Maximum salary: 12000

That's all for this topic Java Stream - max() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - skip() With Examples
  2. Java Stream - limit() With Examples
  3. Java Stream - filter() With Examples
  4. Java Stream - distinct() With Examples
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Invoke Method at Runtime Using Java Reflection API
  2. Transient Keyword in Java With Examples
  3. PreparedStatement Interface in Java-JDBC
  4. String Pool in Java
  5. Writing a File Asynchronously Java Program
  6. Spring Transaction Attributes - Propagation And Isolation Level Settings
  7. Spring MVC - Binding List of Objects Example
  8. Angular CanActivateChild Guard to protect Child Routes

No comments:

Post a Comment