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());
}
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));