사용자 도구

사이트 도구


java:8:stream

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
java:8:stream [2017/11/21 15:29]
kwon37xi [Null safe stream]
java:8:stream [2022/04/09 00:10] (현재)
kwon37xi [parallelStream]
줄 43: 줄 43:
  
 </code> </code>
 +
 +===== Collectors.toMap =====
 +  * ''Collectors.toMap(key function, value function[, mergeFunction])''
 +  * 보통은 Key 하나에 값이 하나 일 때 사용.
 +  * Key 하나에 값이 여러개가 나오는 충돌에 대해 ''merge'' 전략을 제공해줘야 할수도 있다.
 +  * 원래 ''HashMap'' 는 ''null'' value를 허용하지만, ''Collectors.toMap''에서는 이게 허용이 안된다.
 +  * 이유는 해당 구현 내부적으로 호출하는 ''HashMap.merge()'' 메소드에서 이를 허용하지 않기 때문.
 +
 +===== Collectors.groupingBy =====
 +  * ''Map'' 을 만들면서 다시 Collectors 의 결과를 값으로 넣는다. 보통은 키 하나에 값이 여러개가 나올 때 사용.
  
 ===== distinct by key ===== ===== distinct by key =====
줄 48: 줄 58:
   * [[https://stackoverflow.com/a/27872852/1051402|별도 Predicate 선언방식]] <code java>   * [[https://stackoverflow.com/a/27872852/1051402|별도 Predicate 선언방식]] <code java>
 public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
-    Map<Object,Boolean> seen = new ConcurrentHashMap<>();+    Map<Object,Boolean> seen = new ConcurrentHashMap<>(); // parallel stream에서 호출할까봐 이렇게 한듯.
     return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;     return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
 } }
줄 60: 줄 70:
   .values();   .values();
 </code> </code>
 +
 +===== parallelStream =====
 +  * [[https://dzone.com/articles/should-i-parallalise-streams|Should I Parallelize Java 8 Streams?]]
 +  * ''parallelStream''은 작업 분배 오버헤드가 발생하기 때문에 CPU 연산작업만 병렬화 할경우에는 오히려 느려지는 경향이 있다.
 +  * DB 조회/API 호출 처럼 순차보다는 병렬이 확실히 더 확실할 때 빼고는 ''parallelStream''은 사용하지 않는게 낫다.
 +  * 그리고 Thread 안정성도 보장해줘야한다.
 +  * 따라서 성능테스트로 완벽하게 더 좋은 성능이 보장되지 않는다면, 그냥 기본적으로 일반 스트림을 사용해야 한다.
 +
 +===== unmodifiable, immutable collection =====
 +  * [[https://medium.com/@hithacker/producing-immutable-list-from-stream-in-java-8-97f96ae3b04f|Producing immutable list from stream in Java 8 - Hiren Thacker - Medium]]
 +
 +<code java>
 +List<Shape> immutableBlues = shapes.stream()
 +                         .filter(s -> s.getColor() == BLUE)
 +                         .collect(collectingAndThen(toList(),
 +                                  Collections::unmodifiableList))
 +</code>
 +  * [[https://www.baeldung.com/java-stream-immutable-collection|Collect a Java Stream to an Immutable Collection]] [[java:guava|Guava]] 21 부터 Collector 가 추가됨.
 +
 +<code java>
 +    List<Integer> list = IntStream.range(0, 9)
 +      .boxed()
 +      .collect(ImmutableList.toImmutableList());
 +</code>
 +
 +<code java>
 +// 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));
 +</code>
 +  * ''ImmutableMap.toImmutableMap()'' 도 사용가능. ''Collectors.toMap'' 과 유사
 +===== 참고 =====
 +  * [[https://www.baeldung.com/java-predicate-chain|Java 8 Predicate Chain | Baeldung]]
 +  * [[https://www.baeldung.com/java-stream-reduce|Guide to Stream.reduce() | Baeldung]]
 +
java/8/stream.1511247544.txt.gz · 마지막으로 수정됨: 2017/11/21 15:29 저자 kwon37xi