8장 스트림

Jasik·2021년 12월 12일
0
int count = 0;
for (String w : words) {
    if (w.length() > 12) {
        count++;
    }
}

long count = words.stream()
    .filter(w -> w.length() > 12)
    .count();

컬렉션과 차이
1. 스트림은 요소를 저장하지 않는다.
2. 원본을 변경하지 않는다.
3. 연산을 가능하면 지연시켜둔다.

filter, map, flatMap

filter 메서드의 인자 Predicate<T>, T를 받아 boolean을 돌려주는 함수

옵션 타입

Optional<T>

생성

Optional.of(obj)
Optional.ofNullable(obj) // obj가 null 이면 이면 Optional.empty() 반환

사용

Optional<String> optionalString = Optional.ofNullable("some string");

String result = optionalString.orElse("");

String result = optionalString.orElseGet(() -> System.getProperty("user.dir"));

String result = optionalString.orElseThrow(IllegalStateException::new);

optionalValue.ifPresent(v -> {/*do something*/});

optionalValue.ifPresent(results.add);

결과 모으기

String[] result = stream.toArray(String[]::new);

List<String> result = stream.collect(Collectors.toList());

Set<String> result = stream.collect(Collectors.toSet());

TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));

IntSummaryStatics summary = stream.collect(Collectors.summarizingInt(String::length));

Map<Integer, String> idToName = people.collect(Collectors.toMap(Person::getId, Person::getName));

Map<Integer, Person> idToPerson = people.collect(Collectors.toMap(Person::getId, Function.identity()));

병렬 스트림

Stream<String> parallelWords = words.parallelStream();

스트림 연산이 병렬로 실행될 때 목적은 차례로 실행됐을 때와 같은 결과를 반환하는 것.

int[] shortWords = new int[12];
words.parallelStream().forEach(
    s -> {
        if (s.length() < 12) {
            shortWords[s.length()]++;
        }
    }
);

위와 같은 코드는 경쟁 조건 (race condition) 을 포함하고 있어 차례로 실행했을 때와 다른 결과를 낸다.

순서에 대한 요구사항이 없다면 더 효율적으로 병렬화할 수 있다.
Stream.unordered 를 통해 순서에 신경 안씀을 나타낸다.
distinct 연산이 순서를 신경 안쓸 때 이점을 얻는 대표적인 예다.

Stream<String> sample = words.parallelStream().unordered().limit(n);
위 코드는 단어의 순서에 상관 없이 100개만을 뽑아낸다.

profile
가자~

0개의 댓글