Advertisement
Deianov

10. Predicate Party

May 24th, 2019
1,216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. //10. Predicate Party!
  2. package E_FunctionalProgramming.Exercises;
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Arrays;
  8. import java.util.Collections;
  9. import java.util.List;
  10. import java.util.function.Predicate;
  11. import java.util.stream.Collectors;
  12.  
  13. class E10 {
  14.     public static void main(String[] args) throws IOException {
  15.  
  16.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  17.         String line = reader.readLine();
  18.  
  19.         List<String> guests = Arrays.stream(line.split("\\s+")).collect(Collectors.toList());
  20.  
  21.         while (!"Party!".equals(line = reader.readLine())) {
  22.  
  23.             String[] commandTokens = line.split("\\s+");
  24.  
  25.             String command = commandTokens[0];
  26.             String predicateType = commandTokens[1];
  27.             String predicateArgument = commandTokens[2];
  28.  
  29.             if (command.equals("Remove")) {
  30.                 guests.removeIf(getPredicate(predicateType, predicateArgument));
  31.             }
  32.             else if (command.equals("Double")) {
  33.  
  34.                 for (int i = 0; i < guests.size(); i++) {
  35.                     String guest = guests.get(i);
  36.                     if (getPredicate(predicateType, predicateArgument).test(guest)) {
  37.                         guests.add(i++, guest);
  38.                     }
  39.                 }
  40.             }
  41.         }
  42.         if (guests.isEmpty()) {
  43.             System.out.println("Nobody is going to the party!");
  44.         } else {
  45.             Collections.sort(guests);
  46.             System.out.println(String.format("%s are going to the party!", String.join(", ", guests)));
  47.         }
  48.     }
  49.  
  50.     private static Predicate<String> getPredicate(String type, String parameter) {
  51.         switch (type) {
  52.             case "StartsWith":
  53.                 return text -> text.startsWith(parameter);
  54.             case "EndsWith":
  55.                 return text -> text.endsWith(parameter);
  56.             case "Length":
  57.                 return text -> text.length() == Integer.parseInt(parameter);
  58.             default:
  59.                 return text -> false;
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement