가자공부하러!

Java 8 Streams (tutorialspoint.com) 본문

공부/영어

Java 8 Streams (tutorialspoint.com)

오피스엑소더스 2019. 5. 18. 09:39

Stream operations and pipelines

Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce.

출처 : https://docs.oracle.com/javase/8/docs/api/



Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. For example, consider the following SQL statement.

  > Stream은 Java 8에서 새로이 소개된 추상 계층이다. Stream을 사용함으로써 SQL문과 유사하게 선언적인 방법으로 데이터를 처리할 수 있다. 아래 SQL 예문을 보자.


1
SELECT max(salary), employee_id, employee_name FROM Employee
cs


The above SQL expression automatically returns the maximum salaried employee's details, without doing any computation on the developer's end. Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.

  > 위 SQL문은 개발자의 어떠한 계산 없이 자동적으로 최대 salary 값을 갖는 employee의 정보를 반환한다. Java의 컬렉션 프레임워크를 사용한다면, 개발자는 반복문을 이용하고 반복점검을 수행해야한다. 또 다른 관심사는 효율성이다. 멀티 코어 프로세서를 쉽게 사용할 수 있으므로 Java 개발자는 오류가 발생할 위험이 높은 병렬 코드 처리를 작성해야만 한다.

To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it.

  > 이러한 문제들을 해결하기 위해 Java 8에서는 개발자가 데이터를 선언적으로 처리하고 구체적인 코드를 작성할 필요없이 멀티 코어 아키텍처를 활용할 수 있도록하는 stream이라는 개념을 도입했다.


What is Stream?

Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream −

  • Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements.

  • Source − Stream takes Collections, Arrays, or I/O resources as input source.

  • Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.

  • Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.

  • Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.


스트림이 뭐에요?

 스트림은 집계 연산을 지원하는 소스의 객체 시퀀스를 나타낸다. 아래 Stream의 특징들을 살펴보자.

> Sequence of elements - stream은 순차적인 방식으로 특정 타입 요소의 집합을 제공한다. stream은 필요에 따라 요소들을 가져오거나 연산한다. stream은 요소를 저장하지 않는다.

> Source - stream은 컬렉션(set, list, map 등), 배열, 입출력 자료를 입력 소스로 받는다.

> Aggregate operations - 스트림은 filter, map, limit, reduce, find ,match 등의 집계 연산을 지원한다.

> Pipelining - 대부분의 스트림 연산은 연산 결과가 파이프라인[각주:1]으로 산출될 수 있도록 스트림 스스로를 리턴한다. 이러한 작업을 중간 작업이라고하며 중간 작업의 기능은 입력을 처리하고 처리 한 다음 출력을 대상으로 반환하는 것이다. collect () 메소드는 스트림의 끝을 표시하기 위해 파이프 라이닝 작업의 끝에서 정상적으로 존재하는 터미널 연산이다.

> Automatic iterations - 스트림 연산은 명시적 반복을 필요로 하는 컬렉션과 대조적으로 제공된 소스 요소에 대해 내부적인 반복을 수행한다.


Generating Streams

With Java 8, Collection interface has two methods to generate a Stream.

  • stream() − Returns a sequential stream considering collection as its source.

  • parallelStream() − Returns a parallel Stream considering collection as its source.

1
2
List<String> strings = Arrays.asList("abc""""bc""efg""abcd","""jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
cs

스트림 생성

Java 8에서 컬렉션 인터페이스는 스트림을 생성하기 위한 두 개의 메서드를 가진다.

> stream() - 컬렉션 소스에 따라 순차적인 스트림을 리턴

> parallelStream() - 컬렉션 소스에 따라 병렬 스트림을 리턴


forEach

Stream has provided a new method ‘forEach’ to iterate each element of the stream. The following code segment shows how to print 10 random numbers using forEach.

1
2
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
cs

forEach

 스트림은 스트림이 갖는 각각의 요소를 반복하기 위해 새로운 메서드 'forEach"를 제공한다. 아래 코드는 forEach를 활용해서 어떻게 10개의 랜덤 숫자를 출력하는지 보여준다.



map

The ‘map’ method is used to map each element to its corresponding result. The following code segment prints unique squares of numbers using map.

1
2
3
4
List<Integer> numbers = Arrays.asList(3223735);
 
//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
cs


map

 'map' 메서드는 각각의 요소를 해당하는 결과값에 매핑해주기(대응시키기) 위해 사용된다. 아래 코드는 맵을 사용하여 숫자들의 제곱값을 고유하게(중복제거) 출력한다.

실행 결과 : { 9, 4, 49, 25 }


filter

The ‘filter’ method is used to eliminate elements based on a criteria. The following code segment prints a count of empty strings using filter.

1
2
3
4
List<String>strings = Arrays.asList("abc""""bc""efg""abcd","""jkl");
 
//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();
cs


filter

 'filter' 메서드는 기준에 의해 요소를 제거하기 위해 사용된다. 아래 코드는 필터를 사용하여 공백 문자열의 갯수를 카운트한다.

실행 결과 : 2


limit

The ‘limit’ method is used to reduce the size of the stream. The following code segment shows how to print 10 random numbers using limit.

1
2
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
cs


 'limit' 메서드는 stream의 사이즈를 줄이기 위해 사용된다. 아래 코드는 limit을 사용하서 10개의 랜덤한 숫자를 출력하는 방법을 보여준다.



sorted

The ‘sorted’ method is used to sort the stream. The following code segment shows how to print 10 random numbers in a sorted order.

1
2
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
cs


 'sorted' 메소드는 stream을 정렬하기 위해 사용된다. 아래 코드는 10개의 랜덤한 숫자를 정렬된 순서로 출력하는 방법을 보여줍니다.


Parallel Processing

parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream.

1
2
3
List<String> strings = Arrays.asList("abc""""bc""efg""abcd","""jkl");
//get count of empty string
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
cs


It is very easy to switch between sequential and parallel streams.

'parallelStream'은 병렬처리를 위한 stream의 대안이다. 아래 parallelStream을 활용하여 공백 문자열을 카운트하고 카운트 값을 출력하는 코드를 확인해보아. 순차 stream과 병렬 stream 간 교체가 용이하다.


Collectors

Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string.

1
2
3
4
5
List<String>strings = Arrays.asList("abc""""bc""efg""abcd","""jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);
cs

 'Collectors'는 stream 요소의 처리결과 값을 합치기 위해 사용된다. Collectors는 list나 string을 리턴한다.

Statistics

With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done.

1
2
3
4
5
6
List numbers = Arrays.asList(3223735);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest number in List : " + stats.getMax());
System.out.println("Lowest number in List : " + stats.getMin());
System.out.println("Sum of all numbers : " + stats.getSum());
System.out.println("Average of all numbers : " + stats.getAverage());
cs

Java8에서 stream 처리가 완료될 때 모든 통계를 계산하기 위해 통계 수집기가 도입되었다.


Stream Example

Create the following Java program using any editor of your choice in, say, C:\> JAVA.

원하는 편집기 (예 : C : \> JAVA)를 사용하여 다음 Java 프로그램을 작성해 보세요.

Java 소스코드 : /Java8Tester.java

실행 결과 : 








  1. 파이프라인이 뭔가요? - https://dotheright.tistory.com/51 [본문으로]

'공부 > 영어' 카테고리의 다른 글

Spring Boot Example - Creating a Form  (0) 2019.07.20
Spring Boot Thymeleaf Asterisk-syntax  (2) 2019.07.20
Comments