Stream이란

전윤지·2021년 12월 8일
0

JAVA

목록 보기
8/10

1. Stream이란?

  • 람다식을 활용하는 기술
  • 배열, 컬렉션 인스턴스에 함수를 조합해 결과를 얻는 방식
    -> 배열과 컬렉션을 함수형으로 처리 가능
  • 병렬처리 가능
    -> 쓰레드를 사용해 많은 요소를 빠르게 처리 가능
  • for, for each문등의 반복 코드를 줄일 수 있음
  • 1) stream 생성, 2) 중개 연산, 3) 최종 연산으로 구성 됨
    -> 객체.Stram생성().중개연산().최종연산();

2. Stream 생성

  • collection, 배열, 람다식, 빈 스트림, 가변 매개변수 등 다양한 데이터에서 생성 가능
// 1) collection에서 stream 생성
ArrayList<Integer> list = new ArrayList<>();
Stream<Integer> stream = list.stream();
stream.forEach(System.out::println);
        
// 2) 배열에서 stream 생성
String[] arr = new String[]{"하나", "셋", "둘"};
Stream<String> stream2 = Arrays.stream(arr);
stream2.forEach(e -> System.out.println(e + " "));

// 3) 지정 범위 stream 생성
IntStream stream3 = IntStream3.range(1,4); // 1~3
stream3.forEach(System.out::println);

// 4) 빈 stream 생성
Stream<Object> stream4 = Stream.empty();

3. 중개 연산

1) stream 필터링

  • filter() : 필터링
  • disticnt() : 중복제거
  • sorted() : 오름차순 정렬
  • limit()
// 2,6,8
IntStream stream1 = IntStream.of(1,2,3,3,5,6,7,7,8,8,8);
        stream1.distinct()
               .filter(n -> n%2 == 0)
               .forEach(e -> System.out.print(e+" "));

2) stream 변환

  • map() : stream 내의 요소들을 하나씩 특정 값으로 변환해줌
  • flatMap() : 중첩 구조를 한 단계 제거 후, 단일 컬렉션으로 만들어 줌
List<String> names = Arrays.asList("Jeny", "Tom", "Sunny");
        Stream<String> stream2 = names.stream();
        stream2.map(s -> s.toUpperCase())
                .forEach(System.out::println);
/* a1
   a2
   b1
   ...
   c3 */
String[][] arrays = new String[][]{ {"a1", "a2"}, {"b1", "b2"}, {"c1", "c2", "c3"} };
        Stream<String[]> stream3 = Arrays.stream(arrays);
        Stream<String> stream4 = stream3.flatMap(s -> Arrays.stream(s));
        stream4.forEach(System.out::println);
        
// a,b       
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
String flattenResult = 
	list.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.joining(","));
ms.println(flattenResult);

4. 최종 연산

  • forEach()
  • reduce() : 누적 값을 구함
  • findFirst() : 조건에 일치하는 요소 중 가장 첫번째 요소 리턴
  • findAny() : 정렬 순서와 관계없이, 가장 먼저 발견되는 요소 리턴
  • anyMatch(), allMatch(), noneMatch() : 일치하는 것이 있는지 검사 후, boolean 값 리턴
  • count(), min(), max()
  • sum(), average()
  • collect() : stream의 결과를 모으기 위한 메소드
    • 스트림을 배열이나 컬렉션으로 변환 : toArray(), toCollection(), toList(), toSet(), toMap()
    • 통계, 연산 메소드와 같은 동작 수행 : counting(), maxBy(), minBy(), summingInt(), averagingInt()
    • 요소 연산 동작 수행 : reducing(), joining()
    • 요소의 그룹화와 분할 : groupingBy(), partitioningBy()
// reduce
List<Integer> cal = Arrays.asList(1,7,5,10,3);
Integer reduce = cal.stream().reduce((x, y) -> x+y).get();
System.out.println("reduce >" + reduce);

// collect (map -> list)
Map<String,Object> map = new HashMap<>();
map.put("name","joon");
map.put("nickname","joo11");
map.put("age",26);

map.values().stream()
            .collect(Collectors.toList())
            .forEach(System.out::println);


출처 : https://ahndding.tistory.com/23

0개의 댓글