자바 8부터 람다와 함께 사용되는 스트림.

아직 자바 8 환경에서 개발해 볼 경험이 없었지만 정리를 미리 해둔다.

 

스트림은 아래와 같은 파이프라인으로 작성한다.

객체집합.스트림생성().중개연산().최종연산() 

1. 스트림 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static void construct() {
  //1. Collection으로 스트림 생성
  //collection.stream();
  List<String> names = Arrays.asList("pyo""sue");
  names.stream();
  
  //2. 배열로 스트림 생성
  //array.stream();
  int[] arr = {123};
  Arrays.stream(arr);  
  
  //3. 스트림 직접 생성
  //Stream.of(~);
  Stream<Integer> stream = Stream.of(1,2,3);   
}
cs

 

2. 중개연산

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private static List<String> names = Arrays.asList("pyo""sue""aron""ballack""pyo");
 
//2. 중개연산
private static void middle() {
  //2-1. Filter : 특정 조건에 부합하는 데이터만 뽑을 때 사용
  long cnt = names.stream().filter(new Predicate<String>() {
     @Override
     public boolean test(String t) {
        return t.contains("y");
     }
  }).count();
  System.out.print("result of counting after filtering : " + cnt);
  System.out.println("\n-----------------------------");
  
  //2-2. Map : 특정 연산을 할 때 사용
  names.stream().map(new Function<StringString>() {
     @Override
     public String apply(String t) {
        return t.concat("@gmail.com");
     }
  }).forEach(x -> System.out.print(x+" "));
  System.out.println("\n-----------------------------");
  
  //2-3. sort : 정렬
  names.stream().sorted((x1, x2)->x1.compareTo(x2)).forEach(x->System.out.print(x+" "));
  System.out.println("\n-----------------------------");
  
  //2-4. limit : 출력 수 제한
  names.stream().limit(2).forEach(x->System.out.print(x+" "));
  System.out.println("\n-----------------------------");
  
  //2-5. distinct : 중복 제거
  names.stream().distinct().forEach(x->System.out.print(x+" "));
  System.out.println("\n-----------------------------");
  
}
 
cs

 

결과

result of counting after filtering : 2
-----------------------------
pyo@gmail.com sue@gmail.com aron@gmail.com ballack@gmail.com pyo@gmail.com
-----------------------------
aron ballack pyo pyo sue
-----------------------------
pyo sue
-----------------------------
pyo sue aron ballack
-----------------------------

3. 최종연산

1
2
3
4
5
6
7
8
private static List<String> names = Arrays.asList("pyo""sue""aron""ballack""pyo");
 
//3. 최종연산
private static void finalOperate() {
  names.stream().forEach(x->System.out.print(x+" "));
  names.stream().count();
  //names.stream().max();
}
cs

 

 

람다보단 개념이 단순해 보이나

적응되는데 시간이 필요할 듯 하다.

 

참고

반응형

+ Recent posts