문서의 이전 판입니다!
StreamSupport.stream(iterable.spliterator(), false) .filter(...) .moreStreamOps(...);
List<List<Object>> list = ... List<Object> flat = list.stream() .flatMap(List::stream) .collect(Collectors.toList());
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()); }
distinct
를 하려면,public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Map<Object,Boolean> seen = new ConcurrentHashMap<>(); // parallel stream에서 호출할까봐 이렇게 한듯. return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } persons.stream().filter(distinctByKey(p -> p.getName());
toMap
이용// 특정 Key 필드로 Map을 만들되 중복 값은 모두 무시 persons.stream() .collect(toMap(Person::getName, Function.identity(), (p1, p2) -> p1)) .values();
parallelStream
은 사용하지 않는게 낫다.List<Shape> immutableBlues = shapes.stream() .filter(s -> s.getColor() == BLUE) .collect(collectingAndThen(toList(), Collections::unmodifiableList))