HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java 8 Stream – Find Max and Min from List

Java 8 Stream – Find Max and Min from List

Learn to find min and max date, number, Char, String or object from stream of comparable elements in easy steps using Comparator.comparing() method.

Table of Contents

Find Min or Max Date
Find Min or Max Number
Find Min or Max Char or String
Find Min or Max Object by key

Find Min or Max Date

To get max or min date from a stream of dates, you can use Comparator.comparing( LocalDate::toEpochDay ) comparator. toEpochDay() function simply increment count of days for a date where day 0 is for 1970-01-01.

LocalDate start = LocalDate.now();
LocalDate end = LocalDate.now().plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());

//Create stream of dates
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
					    	.limit(ChronoUnit.DAYS.between(start, end))
					    	.collect(Collectors.toList());

// Get Min or Max Date
LocalDate maxDate = dates.stream()
							.max( Comparator.comparing( LocalDate::toEpochDay ) )
							.get();

LocalDate minDate = dates.stream()
							.min( Comparator.comparing( LocalDate::toEpochDay ) )
							.get();

System.out.println("maxDate = " + maxDate);
System.out.println("minDate = " + minDate);

Program Output.

maxDate = 2017-10-30
minDate = 2017-09-13

Use above program to find earliest date or latest date from a list of dates.

Find Min or Max Number

To find min and max number from stream of numbers, use Comparator.comparing( Integer::valueOf ) like comparators. Below example is for stream of Integers.

// Get Min or Max Number
Integer maxNumber = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
					.max(Comparator.comparing(Integer::valueOf))
					.get();

Integer minNumber = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
					.min(Comparator.comparing(Integer::valueOf))
					.get();

System.out.println("maxNumber = " + maxNumber);
System.out.println("minNumber = " + minNumber);

Program Output.

maxNumber = 9
minNumber = 1

Find Min or Max char or String

To find min and max string or char from stream of chars, use Comparator.comparing( String::valueOf ) like comparators.

// Get Min or Max String/Char
String maxChar = Stream.of("H", "T", "D", "I", "J")
						.max(Comparator.comparing(String::valueOf))
						.get();

String minChar = Stream.of("H", "T", "D", "I", "J")
						.min(Comparator.comparing(String::valueOf))
						.get();

System.out.println("maxChar = " + maxChar);
System.out.println("minChar = " + minChar);

Program Output.

maxChar = T
minChar = D

Find Min or Max Object by key

Object comparison involve creating your own custom comparator, first. For example, if I want to get the youngest employee from a stream of Employee objects, then my comparator will look like Comparator.comparing(Employee::getAge). Now use this comparator to get max or min employee object.

Java program to find max or min employee object by it’s age.

List<Employee> employees = new ArrayList<Employee>();

employees.add(new Employee(1, "Lokesh", 36));
employees.add(new Employee(2, "Alex", 46));
employees.add(new Employee(3, "Brian", 52));

Comparator<Employee> comparator = Comparator.comparing( Employee::getAge );

// Get Min or Max Object
Employee minObject = employees.stream().min(comparator).get();
Employee maxObject = employees.stream().max(comparator).get();

System.out.println("minObject = " + minObject);
System.out.println("maxObject = " + maxObject);

Program Output.

minObject = Id:- 1 Name:- Lokesh Age:- 36
maxObject = Id:- 3 Name:- Brian Age:- 52

Where Employee object is:

class Employee {
	private int id;
	private String name;
	private int age;

	public Employee(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		StringBuilder str = null;
		str = new StringBuilder();
		str.append("Id:- " + getId() + " Name:- " + getName() + " Age:- " + getAge());
		return str.toString();
	}
}

In this tutorial, we learned to find max value or min value from a stream of primitive values using Java 8 lambda expression. We also learned to find max or min object such as max Date or String.

We also learned to find max object by object property from stream of objects.

Drop me your questions in comments.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Mahipal

    April 9, 2019

    kindly write a program for second highest number using java 8 given list of numbers

    • Lokesh Gupta

      April 9, 2019

      See if it helps.

      List&lt;Integer&gt; list = Arrays.asList(1,3,4,5,2,8,9,3,6,10,23,2,5);
      
      Optional&lt;Integer&gt; value = list.stream()
      							.sorted(Collections.reverseOrder())
      							.limit(2)
      							.skip(1)
      							.findFirst();
      
      System.out.println(value);
      
  2. Nitin Vashisth

    June 11, 2018

    Is there any way if we want our comparator object to be capable of using more than 1 property of the Employee object so that we can sort the elements based on multiple properties rather than only 1 property.

    • Lokesh Gupta

      June 11, 2018

      Implement compare() method and implement your logic the way you want. There is no restriction.

    • Jagabandhu Malick

      March 22, 2020

      we can use Comarator multComparator = Comparato.comparing(property1).thenComparing(property2);

  3. mingyuC

    June 6, 2018

    no,it will throw an exception,but you can use filter to filter it

  4. chinijo

    December 12, 2017

    Hello Lokesh,
    What about with a list that include null elements? Its possible filter this null elements?
    Thanks!

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)