In this post, we will see “How to check odd or even numbers within a certain range using Java 8 Streams API”.
Easiest representation of Java 8 Streams power to test Odd or Even numbers within a certain range...!!! Share on X
Let’s say: In this particular example, we are extracting the odd and even numbers within the range of 10 to 25
Note: you can specify any range you would like to check for in place of the one we used in this example.
Example
import java.util.stream.*;
public class CheckOddOrEvenNumberWithinRangeJava8 {
public static void main(String args[]) {
retrieveOddNumbersWithinRange(10, 25);
retrieveEvenNumbersWithinRange(10, 25);
}
public static void retrieveOddNumbersWithinRange(int start, int end) {
System.out.println("ODD NUMBERS WITHIN THE RANGE OF 10 AND 25");
//1st way
System.out.println("\n 1st way: \n");
IntStream.range(start, end + 1).filter(i - > i % 2 != 0).forEach(System.out::println);
//2nd way (traditional way - before java 8)
System.out.println("\n 2nd way: \n");
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
//3rd way
System.out.println("\n 3rd way: \n");
Stream.iterate(start, i - > i + 1).filter(CheckOddOrEvenNumberWithinRangeJava8::isOdd).limit(8).forEach(System.out::println);
}
public static void retrieveEvenNumbersWithinRange(int start, int end) {
System.out.println("\n\n EVEN NUMBERS WITHIN THE RANGE OF 10 AND 25");
//1st way
System.out.println("\n 1st way: \n");
IntStream.range(start, end + 1).filter(i - > i % 2 == 0).forEach(System.out::println);
//2nd way (traditional way - before java 8)
System.out.println("\n 2nd way: \n");
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
//3rd way
System.out.println("\n 3rd way: \n");
Stream.iterate(start, i - > i + 1).filter(CheckOddOrEvenNumberWithinRangeJava8::isEven).limit(8).forEach(System.out::println);
}
public static boolean isOdd(int number) {
return number % 2 != 0;
}
public static boolean isEven(int number) {
return number % 2 == 0;
}
}
Output:
ODD NUMBERS WITHIN THE RANGE OF 10 AND 25 1st way: 11 13 15 17 19 21 23 25 2nd way: 11 13 15 17 19 21 23 25 3rd way: 11 13 15 17 19 21 23 25 EVEN NUMBERS WITHIN THE RANGE OF 10 AND 25 1st way: 10 12 14 16 18 20 22 24 2nd way: 10 12 14 16 18 20 22 24 3rd way: 10 12 14 16 18 20 22 24
Easiest representation of Java 8 Streams power to test Odd or Even numbers within a certain range...!!! Share on X
That’s it, Java 8 Streams API is so powerful and notice how shortened and understandable the code is.
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams