As a result of doing a programming quiz at work, two people got the same answer, so make a note
A programming quiz like FizzBuzz. This time we will challenge the problems listed in CodeEval.
CodeEval - https://www.codeeval.com/browse/30/
The input value is a list of two sorted numbers (in ascending order).
The list is separated by ;, and the numbers in the list are separated by ,.
Outputs duplicate numbers in two types of lists, separated by ,.
Input value sample
1,2,3,4;4,5,6
20,21,22;45,46,47
7,8,9;8,9,10,11,12
Output value sample
4
(No output)
8,9
Such an image
java SetIntersection "1,2,3,4;4,5,6"
It has become a one-liner in many ways. (No modularization or exception handling is considered)
import java.util.Arrays;
import java.util.stream.Collectors;
public class SetIntersection {
  public static void main(String[] args) {
    System.out.println(String.join(",",
        Arrays.stream(args[0].split(";")[0].split(","))
            .filter(leftString -> Arrays.stream(args[0].split(";")[1].split(",")).anyMatch(leftString::equals))
            .collect(Collectors.toList())));
  }
}
Use filter to narrow down and list only those that meet the conditions of ʻanyMatch.  The rest is to output with String.join` separated by commas.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SetIntersection {
  private static final String SEPARATOR_LIST = ";";
  private static final String SEPARATOR_NUMBER = ",";
  public static void main(String[] args) {
    Stream<String> leftSide = Arrays.stream(args[0].split(SEPARATOR_LIST)[0].split(SEPARATOR_NUMBER));
    List<String> rightSide = Arrays.asList(args[0].split(SEPARATOR_LIST)[1].split(SEPARATOR_NUMBER));
    System.out.println(String.join(SEPARATOR_NUMBER,
                                   leftSide.filter(leftString -> rightSide.stream().anyMatch(leftString::equals))
                                           .collect(Collectors.toList())));
  }
}
The answer at work was divided into the method using for and ʻif and the method using stream`.
Needless to say, the former has a faster execution speed.
Recommended Posts