Functional-2

noNeg

public List<Integer> noNeg(List<Integer> nums) {
  return nums.stream()
    .filter(n -> n >= 0)
    .collect(Collectors.toList());
}
public List<Integer> noNeg(List<Integer> nums) {
    nums.removeIf(n -> n < 0);
    return nums;
}

no9

public List<Integer> no9(List<Integer> nums) {
  nums.removeIf(n -> n % 10 == 9);
  return nums;
}
  • 아래의 코드로 실행할 경우 아래와 같은 에러 메시지가 뜬다.

    • incompatible types: boolean cannot be converted to java.util.List<java.lang.Integer> line:

public List<Integer> no9(List<Integer> nums) {
  return nums.removeIf(n -> n % 10 == 9);
}

noTeen

public List<Integer> noTeen(List<Integer> nums) {
  nums.removeIf(n -> n <= 19 && n >= 13);
  return nums;
}

noZ

public List<String> noZ(List<String> strings) {
  strings.removeIf(s -> s.contains("z"));
  return strings;
}

noLong

public List<String> noLong(List<String> strings) {
  strings.removeIf(s -> s.length() >= 4);
  return strings;
}

no34

public List<String> no34(List<String> strings) {
  strings.removeIf(s -> s.length() == 3 || s.length() == 4);
  return strings;
}

noYY

Question

Given a list of strings, return a list where each string has "y" added at its end, omitting any resulting strings that contain "yy" as a substring anywhere.

  • diff betwwen filter vs removeIf

public List<String> noYY(List<String> strings) {
  strings = strings.stream()
    .map(s -> s + "y")
    // .removeIf(s -> s.contains("yy"))
    .filter(s -> !s.contains("yy"))
    .collect(Collectors.toList());
  return strings;
}
  • 아래 코드는 틀림

public List<String> noYY(List<String> strings) {
  strings = strings.stream()
    .map(s -> s + "y")
    .filter(s -> !s.matches("(.*)yy"))
    .collect(Collectors.toList());
  return strings;
}

Ref

two2

  • key point : .filter(n -> n % 10 != 2)

public List<Integer> two2(List<Integer> nums) {
  nums = nums.stream()
    .map(n -> n*2)
    .filter(n -> n % 10 != 2)
    .collect(Collectors.toList());
  return nums;
}

square56

public List<Integer> square56(List<Integer> nums) {
  nums = nums.stream()
    .map(n -> n*n + 10)
    .filter(n -> n%10 != 5 && n%10 != 6)
    .collect(Collectors.toList());
  return nums;
}

Last updated