desislava_topuzakova

02. Change List

Oct 16th, 2021
927
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. package Lists_Exercise;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.stream.Collectors;
  7.  
  8. public class ChangeList_02 {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         List<Integer> numbers = Arrays.stream(scanner.nextLine().split(" "))
  12.                 .map(Integer::parseInt).collect(Collectors.toList());
  13.         //"1 2 3 4" -> split(" ") -> ["1", "2", "3", "4"] -> map -> [1, 2, 3, 4] -> {1, 2, 3, 4}
  14.  
  15.         String command = scanner.nextLine(); // "Delete {element}" or "Insert {element} {position}"
  16.         //•   "Delete 5" -> split -> ["Delete", "5"]
  17.         //•   "Insert 10 1" -> split -> ["Insert", "10", "1"]
  18.         while(!command.equals("end")) {
  19.                 String commandName = command.split(" ")[0]; //"Delete" or "Insert"
  20.                 int element = Integer.parseInt(command.split(" ")[1]);
  21.                 if (commandName.equals("Delete")) {
  22.                     numbers.removeAll(Arrays.asList(element));
  23.                 } else if (commandName.equals("Insert")) {
  24.                     int position = Integer.parseInt(command.split(" ")[2]);
  25.                     numbers.add(position, element);
  26.                 }
  27.             command = scanner.nextLine();
  28.         }
  29.  
  30.         for (int number : numbers) {
  31.             System.out.print(number + " ");
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment