Stream API
Stream API는 Collection, 배열 등의 데이터 소스로부터 데이터를 추출하고 조작하는데 유용한 기능을 제공합니다. Stream API는 람다식과 메소드 참조를 이용하여 간결한 코드로 데이터 처리를 할 수 있도록 합니다.
아래 코드들을 통해서 몇가지 사용예시를 통해 이해해보도록하자!
1번 filter()메소드
- filter() 메소드는 요소를 하나씩 확인하면서 조건에 맞는 요소만 반환합니다.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = numbers .stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList());위의 코드는 정수 리스트에서 짝수 요소만 추출하는 예시입니다.
2번 map() 메소드
- map() 메소드는 Stream 객체의 각 요소를 지정된 함수로 변환합니다.
List<String> words = Arrays.asList("hello", "world"); List<String> upperCaseWords = words .stream() .map(String::toUpperCase) .collect(Collectors.toList());위의 코드는 문자열 리스트의 각 요소를 대문자로 변환하는 예시입니다.
3번 sorted() 메소드
- sorted() 메소드는 Stream 객체의 요소를 정렬합니다.
List<NoData> sortedNoDatum = noDatum .stream() .sorted(Comparator.comparingInt(NoData::getNo)) .collect(Collectors.toList());위의 코드는 NoData 객체를 No 속성 값을 기준으로 오름차순 정렬하는 예시입니다.
그러면 내림 차순을 할려면?List<NoData> sortedNoDatum = noDatum .stream() .sorted(Comparator.comparingInt(NoData::getNo).reversed()) .collect(Collectors.toList());reversed를 이용하면 가능합니다!
4번 reduce() 메소드
- reduce() 메소드는 Stream 객체의 요소를 이용하여 하나의 결과값을 생성합니다.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers .stream() .reduce(0, (a, b) -> a + b);위 코드는 정수 리스트의 모든 요소를 더하는 예시입니다.
+. collect메소드(Collectors.toList()) 와 .collect(Collectors.joining(" ")); 무슨 의미인지 알아보겠습니다.
.collect(Collectors.toList())?
Stream 객체를 List 컬렉션으로 변환하는 메소드입니다.
.collect(Collectors.joining(" "))?
joining() 메서드를 사용하여 배열의 모든 요소를 하나의 문자열로 결합할 수 있습니다.
Stream 객체의 요소들을 지정한 "구분자"로 연결하여 하나의 문자열로 반환하는 메소드입니다. 위 코드에서는 공백(" ")으로 문자열을 구분하고 있어서, " "가 구분자라고 할 수 있습니다. 예시 1번과 2번을 출력해보세요
예시1)String[] words = {"Hello", "world", "!"}; String sentence = Arrays.stream(words) .collect(Collectors.joining()); System.out.println(sentence); // "Helloworld!"예시2)
String[] words = {"Hello", "world", "!"}; String sentence = Arrays.stream(words) .collect(Collectors.joining(" ")); System.out.println(sentence); // "Hello world !"
왜 스트림 API를 쓰는가??
기존에는 반복문 등을 이용하여 처리했던 작업들을 간결하게 처리할 수 있으며, 람다식과 메소드 참조를 이용하여 가독성 높은 코드를 작성할 수 있습니다.