Java Stream reduce to get max value on custom object attribute

Introduction

The following code prints the details of the highest earner in the language's list.

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

public class Main {
   public static void main(String[] args) {
      Language[] langArray = { //
            new Language("CSS",  55555), //
            new Language("HTML", 66666), //
            new Language("Java", 44444.5), //
            new Language("Javascript", 77777.77), //
            new Language("C++", 88888), //
            new Language("C",   33333), //
            new Language("SQL", 99999.4) };//

      List<Language> langList = Arrays.asList(langArray);

      langList.stream().forEach(System.out::println);

      Optional<Language> person = 
          langList/*from w  w  w . j  a v  a2 s  . c o  m*/
          .stream()
          .reduce((p1, p2) -> p1.getSalary() > p2.getSalary() ? p1 : p2);
      
      if (person.isPresent()) {
         System.out.println("Highest:" + person.get());
      } else {
         System.out.println("Could not  get   the   highest earner.");
      }
   }
}

class Language {
   private String firstName;
   private double salary;

   public Language(String firstName, double salary) {
      this.firstName = firstName;
      this.salary = salary;
   }

   public String getFirstName() {
      return firstName;
   }

   public double getSalary() {
      return salary;
   }

   @Override
   public String toString() {
      return String.format("%-20s %8.2f", getFirstName(), getSalary());
   }
}



PreviousNext

Related