In this tutorial, we will see “How to find the maximum and minimum of two numbers without using if-else but in fact with the help of streams in Java 8?”
find max and min of two numbers using Java 8 Streams
Java 8 – How to find the max and min of two numbers without using if-else statements? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * Find the find the maximum and minimum of two numbers in array without using if-else statements in Java 8 * @author Deepak Verma * */ import java.util.stream.IntStream; public class Find_max_min_of_two_number_without_using_ifelse_in_Array_using_Java8 { public static void main(String[] args) { int x = 80; int y = 900; int[] arrayOfNumbers = {x, y}; // Finding the minimum of two numbers int minNumber = IntStream.of(arrayOfNumbers).min().getAsInt(); System.out.println("Minimum: " + minNumber); // Finding the maximum of two numbers int maxNumber = IntStream.of(arrayOfNumbers).max().getAsInt(); System.out.println("Maximum: " + maxNumber); } } |
Output:
1 2 | Minimum: 80 Maximum: 900 |
find max and min of two numbers using Java 8 Streams
In the above example, It uses Java 8’s IntStream
class to convert an array of integers into a stream, and then finds the minimum and maximum values using the min()
and max()
methods, respectively.
Java 8 – How to find the max and min of two numbers without using if-else statements? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: