Spring/JAVA

[Java8 Lambda] Streams

alsruds 2023. 10. 20. 01:48
🤹‍♂️Java Brains 강의🤹‍♂️

https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3

 

✅ Streams : A sequence of elements supporting sequential and parallel aggregate operations

 

stream()

✔️ Returns a sequential stream with this collection as its source

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Charles", "Dickens", 60),
                new Person("Lewis", "Carroll", 42),
                new Person("Thomas", "Carlyle", 51),
                new Person("Charlotte", "Bronte", 45),
                new Person("Matthew", "Arnold", 39)
        );

        // LastName 이 C 로 시작하는 사람 출력하기
        people.stream()
                .filter(p -> p.getLastName().startsWith("C"))
                .forEach(p -> System.out.println(p.getFirstName()));

        // LastName 이 C 로 시작하는 사람 수 출력하기
        long count = people.stream()
                .filter(p -> p.getLastName().startsWith("C"))
                .count();
        System.out.println(count);
    }
}

출력 결과

· filter() : returns a stream consisting of the elements of this stream that match the given predicate

· count() : provides a count of elements in that stream

 

parallelStream()

✔️ Returns a possibly parallel stream with this collection as its source

✔️ Split the collection into multiple streams

✔️ Do the exact same thing with .stream()

...
public class Main {
    public static void main(String[] args) {
        ...
        people.parallelStream()
                .filter(p -> p.getLastName().startsWith("C"))
                .forEach(p -> System.out.println(p.getFirstName()));
    }
}

출력 결과