In this tutorial, we will learn how to find out the min and max value from a stream of comparable elements such as characters, strings, dates etc.
We use the min() and max() methods to find the min & max value in streams. These methods are used for finding min & max values in different types of streams such as stream of chars, strings, dates etc. We just have to change the parameter that we pass in this method based on the type of stream.
For example:
max(Comparator.comparing(Integer::valueOf)): To get the max value from stream of numbers.
max(Comparator.comparing(LocalDate::toEpochDay)): To get the max date from stream of dates.
As you can see we have used the Comparator.comparing() method to compare elements of stream. This same method is used for comparing elements of all types of streams such as stream of chars, strings, dates etc. Only the parameter will change based on the type of stream.
Finding min and max number from a stream of numbers
In this example we are finding the min and max value from a stream of numbers.
import java.util.Comparator; import java.util.stream.*; public class JavaExample{ public static void main(String args[]) { //getting max number Integer maxnum = Stream.of(10, 13, 4, 9, 2, 100) .max(Comparator.comparing(Integer::valueOf)) .get(); //getting min number Integer minnum = Stream.of(10, 13, 4, 9, 2, 100) .min(Comparator.comparing(Integer::valueOf)) .get(); System.out.println("Max number is: " + maxnum); System.out.println("Min number is: " + minnum); } }
Output:
Finding min and max date from stream of dates
Lets find the min and max date from a stream of dates using min and max method.
import java.util.Comparator; import java.time.LocalDate; import java.util.List; import java.util.Arrays; public class JavaExample{ public static void main(String args[]) { List<LocalDate> dates = Arrays.asList(LocalDate.now(), LocalDate.now().minusDays(9), LocalDate.now().minusMonths(2), LocalDate.now().minusDays(30)); //getting max date LocalDate maxdate = dates.stream() .max( Comparator.comparing( LocalDate::toEpochDay ) ) .get(); //getting min date LocalDate mindate = dates.stream() .min( Comparator.comparing( LocalDate::toEpochDay ) ) .get(); System.out.println("Max Date is: " + maxdate); System.out.println("Min Date is: " + mindate); } }
Output:
Finding the string with min & max first character
import java.util.Comparator; import java.util.stream.*; public class JavaExample{ public static void main(String args[]) { // Get Min or Max String/Char String maxFirstChar = Stream.of("Aryan", "Tom", "Harry", "Steve") .max(Comparator.comparing(String::valueOf)) .get(); String minFirstChar = Stream.of("Aryan", "Tom", "Harry", "Steve") .min(Comparator.comparing(String::valueOf)) .get(); System.out.println("String with max first char: " + maxFirstChar); System.out.println("String with min first char: " + minFirstChar); } }
Output:
Leave a Reply