문서의 이전 판입니다!
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))
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));