람다식 - 메서드를 하나의 식으로 표현한 것
Stream - 스트림은 1회용이다.
.sorted() // 기본정렬
.sorted(Comparator.reverseOrder()) // 까꾸루
...
Stream을 정렬할 때에는 Comparator
인터페이스를 사용, 조건을 추가 할때에는 thenComparing()
을 사용한다.
// 학생 스트림을 반,성적, 이름순으로 정렬하여 출력하는 예제
studentStream.sorted(Comparator.comparing(Student::getBan)
.thenComparing(Student::getTotalScore)
.thenComparing(Student::getNAME)
.forEach(System.out::println);
Stream의 map()
원하는 필드만 뽑아내거나 특정 형태로 변환해야 할때
Stream<File> fileStream = Stream.of(new File("Ex1.java"), new File("Ex1"), new File("Ex1.bak") ,new File("Ex2.java"), new File("Ex1.txt"));
fileStream.map(File::getName) // 파일이름 뽑고
.filter(s -> s.indexOf('.')!= -1) // 확장자 없는것 제외 하고
.map(s -> s.substring(s.indexOf('.')+1)) // 확장자만 추출하고
.map(String::toUpperCase) // 대문자 변환하고
.distinct() // 중복제거 하고
.forEach(System.out::print); // print
Stream의 peek()
스트림의 요소를 소모하지 않음
fileStream.map(File::getName) // 파일이름 뽑고
.filter(s -> s.indexOf('.')!= -1) // 확장자 없는것 제외 하고
.peek(s -> System.out.printf("filename=%s%n", s)) //파일명 출력
.map(s -> s.substring(s.indexOf('.')+1)) // 확장자만 추출하고
.peek(s -> System.out.printf("extension=%s%n", s)) //확장자명 출력
.map(String::toUpperCase) // 대문자 변환하고
.distinct() // 중복제거 하고
.forEach(System.out::print); // print
Stream의 flatMap()
스트림의 타입이 <T[]>
일때 <T>
로 변환할때 flatMap()을 사용한다.
Optional <T>
T타입의 객체를 감싸는 래퍼클래스. 모든타입의 객체를 담을 수 있다.
Stream의 reduce() - 활용도가 매우 높음