스트림 API란 무엇입니까?
Stream API는 기능적 스타일로 데이터 구조를 사용하는 새로운 방법입니다. 스트림 API(한 컴퓨터 프로그램이 다른 프로그램과 통신할 수 있는 방식에 대한 설명)는 기본적으로 데이터 스트림입니다. "스레드"라는 용어 자체는 일반적인 프로그래밍, 특히 Java에서는 매우 모호합니다.List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
list.add("Six");
list.add("Seven");
list.add("Eight");
list.add("Nine");
list.add("Ten");
Stream stream = list.stream();
위에서 언급했듯이 Stream API를 사용하면 코드 줄 수를 줄일 수 있습니다. 스트림의 예:
IntStream.of(50, 60, 70, 80, 90, 100, 110, 120).filter(x -> x < 90).map(x -> x + 10)
.limit(3).forEach(System.out::print);
스레드가 없는 예:
int[] arr = {50, 60, 70, 80, 90, 100, 110, 120
int count = 0;
for (int x : arr) {
if (x >= 90) continue;
x += 10;
count++;
if (count > 3) break;
System.out.print(x);
}
스트림을 생성하는 가능한 방법:
- 빈 스트림:
Stream.empty()
- 목록에서 스트리밍:
list.stream()
- 지도에서 스트리밍:
map.entrySet().stream()
- 어레이에서 스트리밍:
Arrays.stream(array)
- 지정된 요소에서 스트리밍합니다.
Stream.of("1", "2", "3")
- 중간 ("게으른"이라고도 함) - 들어오는 요소를 처리하고 스트림을 반환합니다. 요소 처리 체인에는 많은 중간 연산자가 있을 수 있습니다.
- 터미널 (“터미널”, “열심히”라고도 함) - 요소를 처리하고 스트림을 종료하므로 체인에는 터미널 운영자가 하나만 있을 수 있습니다.
1.List<String> list = new ArrayList<String>();
2.list.add("One");
…
11.list.add("Ten");
12.Stream stream = list.stream();
13.stream.filter(x-> x.toString().length() == 3).forEach(System.out::println);
무슨 일이야?
- 1 - 목록을 만듭니다
list
. - 2-11 - 테스트 데이터로 채운다;
- 12 - 객체를 생성합니다
Stream
; - 13 - 메서드
filter
(필터) - 중간 연산자는x
열거용 컬렉션의 한 요소와 동일하며( 와 같이for each
) -> 이후에는 컬렉션이 필터링되는 방법을 나타내며 이것이 중간 연산자이므로 필터링된 컬렉션은 메서드로 더 나아갑니다. ,forEach
이는 열거형의 터미널(최종) 아날로그입니다 .for each
(표현식 은System.out::println
다음과 같이 축약x-> System.out.println(x))
되어 전달된 컬렉션의 모든 요소를 통과하여 표시합니다.)
- 터미널 교환원이 호출될 때까지 처리가 시작되지 않습니다.
list.stream().filter(s -> s > 5)
(목록에서 단일 요소를 가져오지 않습니다) - 스트림 인스턴스는 두 번 이상 사용할 수 없습니다. =( ;
그러므로 새로운 것이 나올 때마다:
list.stream().filter(x-> x.toString().length() == 3).forEach(System.out::println);
list.stream().forEach(x -> System.out.println(x));
하나의 스트림에는 여러 개의 중간 연산자가 호출될 수 있지만 터미널 연산자는 하나만 있습니다.
stream.filter(x-> x.toString().length() == 3).map(x -> x + " - the length of the letters is three").forEach(x -> System.out.println(x));
filter(Predicate predicate)
조건을 통과하는 요소만 전달하여 스트림을 필터링합니다(Predicate는 Java SE 8의 패키지에 추가된 내장 기능 인터페이스입니다. " true " 및 " falsejava.util.function
" 값을 확인합니다 ).map(Function mapper)
각 요소를 변경하고 더 이상 건너뛸 함수를 생성할 수 있습니다(기능 인터페이스는Function<T,R>
T 유형의 객체에서 R 유형의 객체로 전환하는 기능을 나타냅니다).flatMap(Function<T, Stream<R>> mapper)
- 의 경우와 마찬가지로map
기본 스트림으로 변환하는 데 사용됩니다.
[stream1,stream2,stream3,stream4] => stream
.
String[] array = {"Java", "Ruuuuussshhh"};
Stream<String> streamOfArray = Arrays.stream(array);
streamOfArray.map(s->s.split("")) //Convert the word to an array of letters
.flatMap(Arrays::stream).distinct() //aligns each generated thread into a single thread
.collect(Collectors.toList()).forEach(System.out::println);
map
스레드 목록(보다 정확하게는 <Stream>
스레드) 으로 변환되는 동안 [stream1,stream2,stream3,stream4] =>Stream.of(stream1,stream2,stream3,stream4)
:
String[] array = {"Java", "Ruuuuussshhh"};
Stream<String> streamOfArray = Arrays.stream(array);
streamOfArray.map(s->s.split("")) //Convert the word to an array of letters
.map(Arrays::stream).distinct() //Make the array into a separate thread
.collect(Collectors.toList()).forEach(System.out::println);
과의 또 다른 차이점은 map
하나의 요소를 0, 하나 또는 다른 여러 요소로 변환할 수 있다는 것입니다. 한 요소를 0개의 요소로 변환하려면 return null
또는 빈 스트림이 필요합니다. 하나의 요소로 변환하려면 예를 들어 를 통해 하나의 요소에서 스트림을 반환해야 합니다 Stream.of(x)
. 여러 요소를 반환하려면 어떤 방법으로든 이러한 요소가 포함된 스트림을 만들 수 있습니다. flatMap 메소드와 동일하지만 Double, Integer 및 Long의 경우:
- flatMapToDouble(함수 매퍼)
- flatMapToInt(함수 매퍼)
- flatMapToLong(함수 매퍼)
Stream.of(2, 3, 0, 1, 3)
.flatMapToInt(x -> IntStream.range(0, x))
.forEach(System.out::print);// 010120012
-
IntStream.range(0,x) – 0(포함)부터 x(비포함)까지의 요소를 스트림으로 출력합니다.
지도:
Stream.of(2, 3, 0, 1, 3) .map(x -> IntStream.range(0, x)) .forEach(System.out::print);//list of streams (streams);
-
limit(long maxSize) – 요소 수로 스트림을 제한합니다.
stream.limit(5).forEach(x -> System.out.println(x));
-
Skip(long n) – n개 요소를 건너뜁니다.
stream.skip(3).forEach(x -> System.out.println(x));
-
정렬()
- sorted(Comparator comparator) – 스트림을 정렬합니다(TreeMap과 같은 정렬):
stream.sorted().forEach(x -> System.out.println(x));
-
distinct() — 스트림에서 요소의 고유성을 확인합니다(요소의 반복 제거).
-
dropWhile(Predicate predicate) - 조건을 만족하는 요소를 건너뜁니다(Java 9에 나타남). Predicate<T> 기능 인터페이스는 일부 조건이 충족되는지 확인합니다. 조건이 충족되면 true가 반환됩니다. 람다 식은 유형의 개체를 사용합니다. T를 매개변수로 사용:
Predicate<Integer> isPositive = x -> x > 0; System.out.println(isPositive.test(3)); // true System.out.println(isPositive.test(-9)); // false
-
forEach(Consumer action) – for Each와 유사합니다(Consumer<T>는 아무것도 반환하지 않고 T 유형의 객체에 대해 일부 작업을 수행합니다).
-
count() – 스트림 요소 수를 반환합니다.
System.out.println(stream.count());
-
Collect(Collector Collector) – 메소드는 모든 요소를 목록, 세트 또는 기타 컬렉션으로 수집하고, 일부 기준에 따라 요소를 그룹화하고, 모든 것을 문자열로 결합하는 등의 작업을 수행합니다.
List<String> list = Stream.of(“One”, “Two”, “Three”).collect(Collectors.toList());
-
collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
— 와 동일하며collect(collector)
편의를 위해 매개변수만 분류됩니다(supplier
예를 들어 는 컨테이너에 요소를 추가하고 스트림의 일부를 결합하는 등 새 개체(컨테이너)를 제공합니다).new ArrayList()
accumulator
combiner
-
Reduce(T ID, BinaryOperator accumulator) - 스트림의 모든 요소를 하나의 객체로 변환하고(모든 요소의 합을 계산하거나 최소 요소를 찾습니다), 먼저 객체
identity
와 스트림의 첫 번째 요소를 가져accumulator
와서 함수를 적용identity
하고 그 결과. 그런 다음 나머지 요소에 대한 모든 작업이 계속됩니다.int sum = Stream.of(1, 2, 3, 4, 5).reduce(10, (acc, x) -> acc + x);// = 25
-
reduce(BinaryOperator accumulator)
— 위와 동일한 방법이지만 초기 방법이 누락되었습니다identity
. 이는 스트림의 첫 번째 요소입니다.Optional min(Comparator comparator)
선택적 max(Comparator comparator)는 전달된 비교기를 기반으로 최소/최대 요소를 검색합니다. -
findFirst()
– 스트림의 첫 번째 요소를 꺼냅니다.Stream.of(1, 2, 3, 4, 9).findFirst();
-
allMatch(Predicate predicate)
— 스트림의 모든 요소가 조건을 만족하면 true를 반환합니다. 조건자 함수 호출 결과가 false 인 요소가 발견되면 연산자는 요소 검색을 중지하고 false를 반환합니다 .Stream.of(1, 2, 3, 4, 9).allMatch(x -> x <= 7);//false
-
anyMatch(Predicate predicate)
— 스트림의 하나 이상의 요소가 조건을 충족하면 true를 반환합니다predicate
.Stream.of(1, 2, 3, 4, 9).anyMatch(x -> x >= 7);//true
-
noneMatch(Predicate predicate)
— 스트림의 모든 요소를 조사한 후 그 중 어느 것도 조건을 만족하지 않으면 true를 반환합니다predicate
.Stream.of(1, 2, 3, 4, 9).noneMatch(x -> x >= 7);//false
Collectors
.
-
toList()
— 요소를 다음으로 수집합니다List
.List<Integer> list = Stream.of(99, 2, 3).collect(Collectors.toList());
-
toSet()
— 요소를 세트로 수집합니다.Set<Integer> set = Stream.of(99, 2, 3).collect(Collectors.toSet());
-
counting()
— 요소 수를 계산합니다.Long count = Stream.of("1", "2", "3", "4").collect(Collectors.counting());
-
joining()
-
joining(CharSequence delimiter)
-
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
— 요소를 한 줄로 수집합니다. 또한 전체 시퀀스에 대한 접두어와 접미어는 물론 구분 기호를 지정할 수 있습니다.String a = Stream.of("s", "u" ,"p", "e", "r").collect(Collectors.joining()); System.out.println(a); // super String b = Stream.of("s", "u", "p", "e", "r").collect(Collectors.joining("-")); System.out.println(b); // s-u-p-e-r String c = Stream.of("s", "u", "p", "e", "r").collect(Collectors.joining(" -> ", "[ ", " ]")); System.out.println(c); // [ s -> u -> p -> e -> r ]
-
summingInt(ToIntFunction mapper)
-
summingLong(ToLongFunction mapper)
-
summingDouble(ToDoubleFunction mapper)
- 객체를 int/long/double로 변환하고 합계를 계산하는 수집기입니다.
GO TO FULL VERSION