목차

Java 8 Stream

Stream for Iterable

List<List<Object>> 같은 컬렉션의 컬렉션 Flatten

List<List<Object>> list = ...
List<Object> flat = 
    list.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());

Null safe stream

public static <T> Stream<T> asStream(Collection<T> collection) {
    return Optional.ofNullable(collection)
        .map(Collection::stream)
        .orElse(Stream.empty());
}
 
public static <T> Stream<T> asStream(T[] array) {
    return Optional.ofNullable(array)
        .map(Arrays::stream)
        .orElse(Stream.empty());
}
 
public static <K, V> Stream<Map.Entry<K, V>> asStream(Map<K, V> map) {
    return Optional.ofNullable(map)
        .map(kvMap -> kvMap.entrySet().stream())
        .orElse(Stream.empty());
}

Collectors.toMap

Collectors.groupingBy

distinct by key

parallelStream

unmodifiable, immutable collection

List<Shape> immutableBlues = shapes.stream()
                         .filter(s -> s.getColor() == BLUE)
                         .collect(collectingAndThen(toList(),
                                  Collections::unmodifiableList))
    List<Integer> list = IntStream.range(0, 9)
      .boxed()
      .collect(ImmutableList.toImmutableList());
// Generic Immutable Collection collector 만들기. 컬렉션 구현체를 원하는대로 선택
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(
  Supplier<A> supplier) {
 
    return Collector.of(
      supplier,
      List::add, (left, right) -> {
        left.addAll(right);
        return left;
      }, Collections::unmodifiableList);
}
 
// 사용예 - LinkedList 구현을 unmodifiable로 감싸기
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
  .collect(MyImmutableListCollector.toImmutableList(LinkedList::new));

참고