예제 #1
1
  static void collectionTest() {
    // removeIf
    Collection<String> c = new HashSet<>();
    c.add("Content 1");
    c.add("Content 2");
    c.add("Content 3");
    c.add("Content 4");
    c.removeIf(s -> s.contains("2"));
    System.out.println("removeIf : " + c);

    /// 基本操作
    List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
    list.removeIf(a -> a % 3 == 0);
    System.out.println("a % 3 == 0 " + list);

    // OR 操作
    Predicate<Integer> predicate2 = a -> a % 3 == 0;
    Predicate<Integer> predicate3 = a -> a % 5 == 0;
    list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
    list.removeIf(predicate2.or(predicate3));
    System.out.println("a % 3 == 0 or a % 5 == 0 " + list);

    // AND 操作
    predicate2 = a -> a % 3 == 0;
    predicate3 = a -> a % 5 == 0;
    list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
    list.removeIf(predicate2.and(predicate3));
    System.out.println("a % 3 == 0 and a % 5 == 0 " + list);

    List<String> stringList = Arrays.asList("a", "b");
    stringList.forEach(System.out::println);

    stringList = Arrays.asList("a", "b", "c");
    stringList.replaceAll(String::toUpperCase);
    System.out.println(stringList); // [A, B, C]

    stringList = Arrays.asList("a", "b", "c");
    stringList.sort(String::compareTo);

    Map<String, Integer> map = new HashMap<>();
    map.put("A", 10);
    map.put("B", 20);
    map.put("C", 30);
    map.forEach((k, v) -> System.out.println("Item : " + k + " Count : " + v));
    System.out.println(map.getOrDefault("D", 40)); // => 40
  }