Didart

Find Evens or Odds

Jan 30th, 2023
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. package FunctionalProgramming;
  2.  
  3. import java.util.Scanner;
  4. import java.util.function.Predicate;
  5. import java.util.stream.IntStream;
  6.  
  7. public class FindEvensOrOdds {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.        
  11.         String[] line = scanner.nextLine().split(" ");
  12.        
  13.         String evenOrOdd = scanner.nextLine();
  14.        
  15.         Predicate<Integer> even = x -> x % 2 == 0;
  16.         Predicate<Integer> odd = x -> x % 2 != 0;
  17.        
  18.         int start = Integer.parseInt(line[0]);
  19.         int end = Integer.parseInt(line[1]);
  20.        
  21.         Predicate<Integer> type = even;
  22.        
  23.         if (evenOrOdd.equals("odd")){
  24.             type = odd;
  25.         }
  26.        
  27.         IntStream.rangeClosed(start, end)
  28.                 .boxed()
  29.                 .filter(type)
  30.                 .forEach(x -> System.out.printf("%d ", x));
  31.     }
  32. }
  33.  
  34.  
Advertisement
Add Comment
Please, Sign In to add comment