Java bootcamp · Lab 48

Set intersection

mediumSet12 minLesson: Set

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read two lines of ints; print sorted intersection space-separated.

Examples

Example 1
Input
1 2 3 4
3 4 5
Output
3 4
Hint
  1. TreeSet retainAll
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    TreeSet<Integer> A = new TreeSet<>();
    for (String s : in.nextLine().trim().split("\\s+")) if (!s.isEmpty()) A.add(Integer.parseInt(s));
    TreeSet<Integer> B = new TreeSet<>();
    for (String s : in.nextLine().trim().split("\\s+")) if (!s.isEmpty()) B.add(Integer.parseInt(s));
    A.retainAll(B);
    boolean first = true;
    for (int x : A) {
      if (!first) System.out.print(' ');
      System.out.print(x);
      first = false;
    }
    System.out.println();
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.