Stream 소개
Stream
- 연속된 데이터를 처리하는 함수.
Stream은 데이터 소스를 변경하지 않는다.
public class App{
public static void main(String[] args){
List<String> names = new ArrayList<>();
names.add("Dante");
names.add("Deok");
names.add("rin");
names.add("Hi");
Stream<Strimg> stringStream = names.stream().map(String::toUpperCase);
names.forEach(System.out::println);
}
출력 :
Dante
Deok
rin
Hi
데이터가 변경되지 않았다 ? Functional in nature
Operator
- 스트림으로 처리하는 데이터는 오직 한번만 처리한다.
- 무제한일 수도 있다. (Short Circuit 메소드를 사용해서 제한할 수 있다.)
- 중개 오퍼레이션은 근본적으로 lazy 하다.
- 손쉽게 병렬 처리할 수 있다.
- 중개(intermediate) 오퍼레이션(이어지는)
map : map 메소드는 주어진 함수를 스트림의 요소에 적용한 결과로 구성된 스트림을 리턴하는데 사용한다.
List num = Arrays.asList(1,2,3,4,5,6);
List square = num.stream().map(x -> x * x).Collectors.toList());
filter : 필터 메소드는 인수로 전달된 조건에 따라 요소를 선택하는데 사용한다.
List names = Arrays.asList("Reflection", "Collection", "Stream");
List result = names.stream().filter(s -> s.startsWith("C")).collect(Collectors.toList());
sorted : sorted 메소드는 스트림을 정렬하는데 사용한다.
List names = Arrays.asList("Reflection", "Collection", "Stream");
List result = names.stream().sorted().collect(Collectors.toList());
- 종료(terminal) 오퍼레이션 (끝)
collect : collect 메소드 스트림에서 수행된 중간 작업의 결과를 반환하는 데 사용된다.
List num = Arrays.asList(2,3,4,5,3);
Set square = num.stream().map(x -> x * x).collect(Collectors.toSet());
forEach : forEach 메서드는 스트림의 모든 요소를 반복하는 데 사용된다.
List num = Arrays.asList(2,3,4,5);
num.stream().map(x -> x * x).forEach(y -> System.out.println(y));
reduce : reduce 메소드는 스트림의 요소를 단일 값으로 줄이는 데 사용된다. reduce 메소드는 BinaryOperator를 매개변수로 사용한다.
List num = Arrays.asList(2,3,4,5);
int even = num.stream().filter(x -> x % 2 == 0).reduce(0,(ans,i)) -> ans + i);
public class App{
public static void main(String[] args){
// create a list of integers
List<Integer> number = Arrays.asList(2,3,4,5);
// demonstration of map method
List<Integer> square = number.stream().map(x -> x*x).collect(Collectors.toList());
System.out.println(square);
// create a list of String
List<String> names = Arrays.asList("Reflection","Collection","Stream");
// demonstration of filter method
List<String> result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> show = names.stream().sorted().collect(Collectors.toList());
System.out.println(show);
// create a list of integers
List<Integer> numbers = Arrays.asList(2,3,4,5,2);
// collect method returns a set
Set<Integer> squareSet = numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
number.stream().map(x->x*x).forEach(y->System.out.println(y));
// demonstration of reduce method
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
System.out.println(even);
}
}
출력 :
[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6