JDK 8에서 추가된 API로 데이터 소스를 추상화 하고, 데이터를 다루는데 자주 사용되는 메서드들을 정의해 놓았다.
데이터 소스의 추상화란 데이터 소스가 무엇이든 같은 방식으로 다룰 수 있게 하는 것을 의미한다.
// stream 사용 전
String[] stringArray = {"naver","kakao","google","toss"};
List<String> stringList = Arrays.asList(stringArray);
Arrays.sort(stringArray);
Collections.sort(stringList);
for(String str : stringArray){
System.out.println(str);
}
for(String str : stringList){
System.out.println(str);
}
// stream 사용 후
Stream<String> arrayStream = stringArray.stream();
Stream<String> listStream = Arrays.stream(stringArray);
arrayStream.sorted().forEach(System.opt::println);
listStream.sorted().forEach(System.opt::println);
List<String> sortedList = listStream.sorted().collect(Collections.toList());
listStream.sorted().forEach(System.out::println);
// 요소들을 모두 대문자로 변경
listStream.map(String::toUpperCase).forEach(System.out::println);
Stream<T[]>
인 경우에 사용하여 Stream<T>
의 형태로 변환한다.// stream의 타입이 T[] 형태
Stream<String[]> arrStream = Stream.of(new String[] {"a", "b", "c"}), new String[] {"d", "e", "f"});
// 첫글자가 n인 요소만 골라서 출력
Stream<String> strStream = Arrays.asList(new String[]{"naver", "kakao", "google", "toss"}).stream();
strStream.filter(str->str.toCharArray()[0] - 'n' == 0).forEach(System.out::println); // naver
collect()
를 사용하여 변수에 할당할 수 있다.// 스트림의 요소를 모아 List<String>의 형태로 반환해준다.
List<String> sortedList = listStream.sorted().collect(Collections.toList());
List<Integer> list = new ArrayList<>(Arrays.asList(1, 12, 15, 7, 8, 10, 88));
System.out.println(list.stream().reduce(Integer::max)); // 88
스트림을 사용하면 반복문을 여러번 사용하지 않고도 손쉽게 Iterable한 요소들에 처리를 할 수 있다. 그러니 생각날 때 사용하는 것도 나쁘지 않을 것 같다.