desislava_topuzakova

08. Custom Comparator

Jun 5th, 2021
800
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. package FunctionalProgramming;
  2.  
  3. import java.sql.SQLOutput;
  4. import java.util.*;
  5. import java.util.function.*;
  6. import java.util.stream.Collectors;
  7.  
  8. public class demo {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         //Function<приема, връща>
  12.         //Consumer<приема>
  13.         //Supplier<връща>
  14.         //Predicate<приема> -> return boolean
  15.         //BiFunction <приема1, приема2, връща>
  16.  
  17.         //взимаме лист и печатаме индексът на най-малкия елемент
  18.         List<Integer> numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
  19.                 .mapToInt(Integer::parseInt)
  20.                 .boxed()
  21.                 .collect(Collectors.toCollection(ArrayList::new));
  22.  
  23.         // а и б четни
  24.         //а четно б нечетно
  25.         //а нечетно б четно
  26.         // а нечетно и б четно
  27.         Comparator<Integer> comparator = ((a, b) -> {
  28.            if (a % 2 == 0 && b % 2 == 0) {
  29.                return a.compareTo(b);
  30.            } else if (a % 2 == 0 && b % 2 != 0){
  31.                return -1;
  32.            } else if (a % 2 != 0 && b % 2 == 0) {
  33.                return +1;
  34.            }
  35.            return a.compareTo(b);
  36.         });
  37.  
  38.  
  39.         numbers.stream().sorted(comparator).forEach(e -> System.out.print(e + " "));
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.     }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment