HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Java 8 Stream – Find Max and Min from List

By Lokesh Gupta | Filed Under: Java 8

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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

6
Leave a Reply

This comment form is under antispam protection
4 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Mahipal

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

Vote Up0Vote Down  Reply
7 months ago
Lokesh Gupta

See if it helps.

List<Integer> list = Arrays.asList(1,3,4,5,2,8,9,3,6,10,23,2,5);

Optional<Integer> value = list.stream()
							.sorted(Collections.reverseOrder())
							.limit(2)
							.skip(1)
							.findFirst();

System.out.println(value);
Vote Up0Vote Down  Reply
7 months ago
Nitin Vashisth

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.

Vote Up0Vote Down  Reply
1 year ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
1 year ago
mingyuC

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

Vote Up0Vote Down  Reply
1 year ago
chinijo

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

Vote Up0Vote Down  Reply
1 year ago

Search Tutorials

Java 8 Tutorial

  • Java 8 – Introduction
  • Java 8 – forEach
  • Java 8 – Stream
  • Java 8 – Boxed Stream
  • Java 8 – Lambda Expression
  • Java 8 – Functional Interface
  • Java 8 – Method References
  • Java 8 – Default Method
  • Java 8 – Optionals
  • Java 8 – 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 – Join Array
  • Java 8 – Base64
  • Java 8 – Exact Arithmetic
  • Java 8 – Comparator
  • Java 8 – Regex as Predicate
  • Java 8 – Join String
  • Java 8 – Difference Between Dates
  • Internal vs. External Iteration
  • Java 8- SecureRandom

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz