desislava_topuzakova

10. Predicate Party!

Sep 30th, 2021
1,273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. import java.lang.reflect.Array;
  2. import java.util.*;
  3. import java.util.function.*;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.IntStream;
  6.  
  7. public class Demo {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         ArrayList<String> guests = Arrays.stream(scanner.nextLine().split("\\s+"))
  12.                 .collect(Collectors.toCollection(ArrayList::new));
  13.  
  14.         String line = scanner.nextLine();
  15.  
  16.  
  17.  
  18.         while (!line.equals("Party!")){
  19.  
  20.             Predicate<String> predicate = null;
  21.  
  22.             String criteria = line.split("\\s+")[2];
  23.  
  24.             if(line.contains("Length")){
  25.                 predicate = x -> x.length() == Integer.parseInt(criteria);
  26.             }else if(line.contains("StartsWith")){
  27.                 predicate = x -> x.startsWith(criteria);
  28.             }else{
  29.                 predicate = x -> x.endsWith(criteria);
  30.             }
  31.  
  32.             if(line.contains("Remove")){
  33.                 ArrayList<String> toRemove = new ArrayList<>();
  34.                 for (String guest : guests) {
  35.                     if(predicate.test(guest)){
  36.                         toRemove.add(guest);
  37.                     }
  38.                 }
  39.  
  40.                 guests.removeAll(toRemove);
  41.             }else{
  42.                 ArrayList<String> toAdd = new ArrayList<>();
  43.                 for (String guest : guests) {
  44.                     if(predicate.test(guest)){
  45.                         toAdd.add(guest);
  46.                     }
  47.                 }
  48.                 guests.addAll(toAdd);
  49.             }
  50.  
  51.             line = scanner.nextLine();
  52.         }
  53.  
  54.         if(guests.isEmpty()){
  55.             System.out.println("Nobody is going to the party!");
  56.         }else{
  57.             System.out.println(guests.stream().sorted().collect(Collectors.toCollection(ArrayList::new)).toString().replaceAll("([\\[\\]])", "") + " are going to the party!");
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment