Java 8 Stream Min Max - onlyxcodes

Friday 29 April 2022

Java 8 Stream Min Max

In this post, you'll learn about the Java 8 Stream API's min() and max() methods.


These methods are used to discover the minimum and maximum values in various types of streams, such as char streams, strings, dates, and so on.


The min() and max() methods take a Comparator as an input parameter, which uses the Comparator.comparing() method to compare the values.


Let's look at min and max methods using some practical Java programs.


java 8 stream min max methods - comparator - reduce - date - localdatetime -bigdecimal - example

Table Content

1. Stream min() method

2. Stream max() method

3. Stream min() and max() Methods Examples

4. Find Min and Max Object from Property Value


1. Stream min() method:

The Stream min method is a terminal operation that reads a stream and returns the smallest element using the Comparator provided.


This is a distinct instance of reduction. Stream.reduce(), for example.


If a minimum value is null, the method throws a NullPointerException.


Syntax:-


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

2. Stream max() method:

The Stream max method is a terminal operation that reads a stream and returns the maximum value based on a Comparator specified.


This is a particular instance of reduction. For instance, take Stream.reduce().


If the maximum value is null, the method throws a NullPointerException.


Syntax:-


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

3. Stream min() and max() Methods Examples

Example: Find Max and Min Number in Stream:


In this example, we use Stream to get the minimum and maximum values.


We first build the Stream and then call the Comparator.comparing(Integer::valueOf) method within the max() and min() methods, which works similarly to comparators.


package com.onlyxcodes;

import java.util.Comparator;
import java.util.stream.Stream;

public class MinMaxNumber 
{
	public static void main(String args[])
	{
		//get max number
		Integer maxNum = Stream.of(9, 7, 11, 36, 4, 18, 70)
				.max(Comparator.comparing(Integer::valueOf))
				.get();
		
		//get min number
		Integer minNum = Stream.of(5, 9, 12, 1, 36, 78, 90)
				.min(Comparator.comparing(Integer::valueOf))
				.get();
		
		System.out.println("Max number is: " +maxNum);
		System.out.println("Min number is: " +minNum);
	}
}

Output:


Max number is: 70
Min number is: 1

Example: Find Max and Min Number from List using Stream


A list of integer numbers from 10 to 50 is shown in this example. To get the minimum and maximum values, we used the min() and max() methods, as well as Comparator.comparing(Integer::valueOf).


Comparator.comparing(Integer::valueOf) operates as a Comparators.


package com.onlyxcodes;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class MinMaxFromList {

	public static void main(String[] args) 
	{
		
		List <Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
		
		int maxNum = numbers
				.stream()
				.max(Comparator.comparing(Integer::valueOf))
				.get();
		
		int minNum = numbers
				.stream()
				.min(Comparator.comparing(Integer::valueOf))
				.get();
		
		System.out.println("Max number value is:  " +maxNum);
		System.out.println("Min number value is:  " +minNum);
	}

}

Output:


Max number value is:  50
Min number value is:  10

Example: Find Min and Max String from First Character


In this example, we use the Comparator.comparing(String::valueOf) method to get the min and max string or character from a stream of the first character.


package com.onlyxcodes;

import java.util.Comparator;
import java.util.stream.Stream;

public class MinMaxString {

	public static void main(String[] args) {
		
		String maxCharFirst = Stream.of("Apple", "Facebook", "Microsoft", "IBM", "Oracle")
				.max(Comparator.comparing(String::valueOf))
				.get();
		
		String minCharFirst = Stream.of("Apple", "Facebook", "Microsoft", "IBM", "Oracle")
				.min(Comparator.comparing(String::valueOf))
				.get();
		
		System.out.println("Max String from First Character: " +maxCharFirst);
		System.out.println("Min String from First Character: " +minCharFirst);
	}

}

Output:


Max String from First Character: Oracle
Min String from First Character: Apple

Example: Find Min and Max Character


In the previous example, we used Comparator.comparing( String::valueOf ) to get min and max string but here we used Comparator.comparing(Character::charValue) to find min and max character.


package com.onlyxcodes;

import java.util.Comparator;
import java.util.stream.Stream;

public class MinMaxChar {

	public static void main(String[] args) 
	{
		char maxChar = Stream.of('o', 'n', 'l', 'y', 'x', 'c', 'o', 'd', 'e', 's')
		        .max(Comparator.comparing(Character::charValue))
		        .get();
		
		
		char minChar = Stream.of('o', 'n', 'l', 'y', 'x', 'c', 'o', 'd', 'e', 's')
		        .min(Comparator.comparing(Character::charValue))
		        .get();

		System.out.println("Max char in Stream is: " + maxChar);
		System.out.println("Min char in stream is: " + minChar);

	}

}

Output:


Max char in Stream is: y
Min char in stream is: c

Example: Find Min and Max Date from Stream of Dates


You can use the Comparator.comparing(LocalDate::toEpochDay) Comparator to get the mx or min date from a stream of dates.


This data is converted to an EpochDay using the toEpochDay() function of the ChronoLocalDate interface. The EpochDay is the number of days since the 0 EpochDay on January 1, 1970. The output will be in ISO-8601 yyyy-MM-dd format.


package com.onlyxcodes;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class MinMaxDate {

	public static void main(String[] args) 
	{

		List<LocalDate> dates = Arrays.asList(LocalDate.now(), 
				LocalDate.now().minusMonths(2));
				
		//get max date
		LocalDate maxdate = dates.stream()
		             .max(Comparator.comparing( LocalDate::toEpochDay))
		             .get();
				 
		//get min date
		LocalDate mindate = dates.stream()
		             .min(Comparator.comparing( LocalDate::toEpochDay))
		             .get();
				 
		System.out.println("The Max Date is: " + maxdate);
		System.out.println("The Min Date is: " + mindate);

	}

}

Output:


The Max Date is: 2022-04-22
The Min Date is: 2022-02-22

Example: Find Min and Max Number and String using Stream.reduce() Method:


The introduction of min and max is a special case of stream reduction that we have already covered.


Using the Streamreduce() method, we get the minimum and maximum integer values as well as the string value in this example.


package com.onlyxcodes;

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

public class MinMaxReduce {

	public static void main(String[] args) 
	{
		
		System.out.println("---Numbers Reduction---");
		
		List<Integer> numberList = Arrays.asList(52, 24, 36, 100);

		
		//getting max number 
		numberList.stream().reduce(Integer::max).ifPresent(res -> System.out.println(res)); //44
		
		//getting min number
		numberList.stream().reduce(Integer::min).ifPresent(res -> System.out.println(res)); 
		
		
		System.out.println("");
		System.out.println("---String Reduction---");
		System.out.println("");
		
		List<String> stringList = Arrays.asList("Microsoft", "Oracle", "Apple", "Facebook");

		//getting min string
		stringList.stream().reduce((str1, str2) -> {
		  if (str1.compareTo(str2) <= 0) {
			return str1;
		  }
		  return str2;
		}).ifPresent(result -> System.out.println(result)); 
		
		
		//getting max string
		stringList.stream().reduce((str1, str2) -> {
		  if (str1.compareTo(str2) >= 0) {
			return str1;
		  }
		  return str2;
		}).ifPresent(result -> System.out.println(result)); 
	}

}

Output:


---Numbers Reduction---
100
24

---String Reduction---

Apple
Oracle

4. Find Min and Max Object from Property Value

In this topic, we use custom objects, a custom comparator, and streams in Java to find the maximum and minimum values of a collection.


Let's say we have the Person POJO class, which has two properties: name and age.


Person.java

package com.onlyxcodes.app;

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

	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() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
		
}

1. Using Stream.max() and Stream.min() Method.


Using custom objects to find the maximum and minimum value of a field.


The main Java class is this. This class has a list of 5 Person objects, each of which has its own name and age.


We apply the Stream.max() and Stream.min() methods to turn the list of objects into a stream of objects.


The methods Stream.max() and Stream.min() accept a Comparator to compare objects based on a field value and return Optional holding the stream's maximum and minimum objects.


The Age field is used, and it is passed to the Comparator.comparingInt() method. The Comparator's comparingInt() static method sorts a list of stuff of any type using an integer sort key.


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
	     
	     // getting a person with the maximum age
	    Person p1 = personsList.stream()
	    	 .max(Comparator.comparingInt(Person::getAge))
	    	 .get();
	     
	    System.out.println("Person who maximum age: " + p1);
	     
	    
	     // getting a person with the minimum age
	    Person p2 = personsList.stream()
	    	 .min(Comparator.comparingInt(Person::getAge))
	    	 .get();
	     
	    System.out.println("Person who minimum age: " + p2);
		
	}

}

Output:


Person who maximum age: Person [name=David, age=55]
Person who minimum age: Person [name=Jhon, age=24]

Using Lambda Function


The lambda function can also be used as a comparator, as shown here:


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
	     
		/**** Using  Lambda Function ***/
		
		 // getting a person with the maximum age
	     Person p1 = personsList.stream()
	    		 .max((a, b) -> a.getAge() - b.getAge())
	    		 .get();
	     
	     System.out.println("Person who maximum age: " + p1);
	     
	    
	     // getting a person with the minimum age
	     Person p2 = personsList.stream()
	    		 .min((a, b) -> a.getAge() - b.getAge())
	    		 .get();
	     
	     System.out.println("Person who minimum age: " + p2);
		
	}

}

Output:


Person who maximum age: Person [name=David, age=55]
Person who minimum age: Person [name=Jhon, age=24]

2. Using Collectors


Collectors can also be used to discover the maximum or minimum object in a list.


Collectors.maxBy() gives a Collector that gets more objects for a specified Comparator. Collectors.minBy(), on the other hand, returns a Collector that returns the smallest item given a Comparator.


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
	     
		/**** Using Collectors  ***/
		
		// getting a person with the maximum age
	     Person p1 = personsList.stream()
	    		 .collect(Collectors.maxBy(Comparator.comparingInt(Person::getAge)))
	    		 .get();
	     
	     System.out.println("Person who maximum age: " + p1);
	     
	    
	     // getting a person with the minimum age
	     Person p2 = personsList.stream()
	    		 .collect(Collectors.minBy(Comparator.comparingInt(Person::getAge)))
	    		 .get();
	     
	     System.out.println("Person who minimum age: " + p2);
	}

}

Output:


Person who maximum age: Person [name=David, age=55]
Person who minimum age: Person [name=Jhon, age=24]

In the Collectors, we may also pass a lambda function as a comparator, as illustrated below:


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
	     
		/**** Using Lambda Function in Collectors  ***/
		
		// getting a person with the maximum age
	     Person p1 = personsList.stream()
	    		 .collect(Collectors.maxBy((a, b) -> a.getAge() - b.getAge()))
	    		 .get();
	     
	     System.out.println("Person who maximum age: " + p1);
	     
	    
	     // getting a person with the minimum age
	     Person p2 = personsList.stream()
	    		 .collect(Collectors.minBy((a, b) -> a.getAge() - b.getAge()))
	    		 .get();
	     
	     System.out.println("Person who minimum age: " + p2);
		 
	}

}

Output:


Person who maximum age: Person [name=David, age=55]
Person who minimum age: Person [name=Jhon, age=24]

3. Using Stream.reduce() Method


The Stream.reduce() method, which gives an Optional representation of the reduced object, can also be used to do a reduction operation on stream components.


We can submit a lambda functionality to the reduction operation in the Java code below, as shown:


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
		
		/**** Using Stream.reduce() method  ***/
		
		Person p1 = personsList.stream()
	    		 .reduce((a, b) -> a.getAge() > b.getAge() ? a : b)
	    		 .get();
	     
	     System.out.println("Person who maximum age: " + p1);
	     
	    
	     // getting a person with the minimum age
	     Person p2 = personsList.stream()
	    		 .reduce((a, b) -> a.getAge() < b.getAge() ? a : b)
	    		 .get();
	     
	     System.out.println("Person who minimum age: " + p2);
		
	}

}

Output:


Person who maximum age: Person [name=David, age=55]
Person who minimum age: Person [name=Jhon, age=24]

We can also use the enhanced reduce() method, who reduces the stream items using the specified uniqueness value and an associative collection process, then returns the reduced result.


package com.onlyxcodes.app;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinMaxObject {

	public static void main(String[] args) 
	{
		List <Person> personsList = new ArrayList <Person> ();
		
		personsList.add(new Person("Jhon", 24));
		personsList.add(new Person("Ronaldo", 36));
		personsList.add(new Person("Messi", 40));
		personsList.add(new Person("Mike", 50));
		personsList.add(new Person("David", 55));
	     
		// getting a person with the maximum age
		Person p1 = personsList.stream()
		                .reduce(new Person("Temporary", Integer.MAX_VALUE),
		                        (i, j) -> i.getAge() < j.getAge() ? i : j);
		
		System.out.println("Person who maximum age: " + p1);
		
		 
		// getting a person with the minimum age
		Person p2 = personsList.stream()
		                .reduce(new Person("Temporary", Integer.MIN_VALUE),
		                        (i, j) -> i.getAge() > j.getAge() ? i : j);
		
		System.out.println("Person who minimum age: " + p2);
		
	}

}

Output:


Person who maximum age: Person [name=Jhon, age=24]
Person who minimum age: Person [name=David, age=55]

No comments:

Post a Comment

Post Bottom Ad