본문
170420(목) - Streams <Intermediate Operations>
Programming/Java 8 2017. 4. 20. 15:09
Streams
- Mapping
ㆍelements의 형태를 변경하는 process
ㆍsql 에서의 select 방식이라고 생각하면 된다.
- map
ㆍstreams element 변경이나 형식 변경에 사용
ㆍ다른 함수를 인수로 취한다.
students.stream()
.map(Student::getName)
.forEach(System.out::println);
- FlatMap
ㆍmap과 별도로 새로 형성된 element의 하위 Stream을 생성
ㆍ마지막에 모든 하위 steam을 단일 steam으로 변경
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> mapped =
numbers.stream()
.map(number -> Arrays.asList(number -1, number, number +1))
.collect(Collectors.toList());
System.out.println(mapped); //:> [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
List<Integer> flattened =
numbers.stream()
.flatMap(number -> Arrays.asList(number -1, number, number +1).stream())
.collect(Collectors.toList());
System.out.println(flattened); //:> [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5]
- Filtering
- filter
ㆍpredicate를 인수로 사용함
//Only the students with score >= 60
students.stream()
.filter(student -> student.getScore() >= 60)
.collect(Collectors.toList());
- Unique Elements
ㆍ중복 요소 제거
//Get distinct list of names of the students
students.stream()
.map(Student::getName)
.distinct()
.collect(Collectors.toList());
- Limiting
ㆍ조건이 만족되면 나머지는 short circuit에 의해서 skip 된다.
//List of first 3 students who have age > 20
students.stream()
.filter(s -> s.getAge() > 20)
.map(Student::getName)
.limit(3)
.collect(Collectors.toList());
- Skipping
ㆍ스킵되는 수가 element 보다 많으면 빈값이 리턴된다.
//List of all the students who have age > 20 except the first 3
students.stream()
.filter(s -> s.getAge() > 20)
.map(Student::getName)
.skip(3)
.collect(Collectors.toList());
- Sorting
students.stream()
.map(Student::getName)
.sorted()
.collect(Collectors.toList());
students.stream()
.sorted(Comparator.comparing(Student::getName))
.map(Student::getName)
.collect(Collectors.toList());
//Sorting names if the Students in descending order
students.stream()
.map(Student::getName)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
//Sorting names if the Students in descending order
students.stream()
.map(Student::getName)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
//Sorting students by First Name and Last Name both
students.stream()
.sorted(Comparator.comparing(Student::getFirstName).
thenComparing(Student::getLastName))
.map(Student::getName)
.collect(Collectors.toList());
//Sorting students by First Name Descending and Last Name Ascending
students.stream()
.sorted(Comparator.comparing(Student::getFirstName)
.reversed()
.thenComparing(Student::getLastName))
.map(Student::getName)
.collect(Collectors.toList());
'Programming > Java 8' 카테고리의 다른 글
170427(목) - Repeating Annotations (0) | 2017.04.27 |
---|---|
170420(목) - Streams <Terminal Operations> (0) | 2017.04.20 |
170420(목) - Streams <Laziness and Performance Optimization> (0) | 2017.04.20 |
170420(목) - Streams <Understanding Java 8 Streams API (0) | 2017.04.20 |
170419(수) - Lambda Expressions (0) | 2017.04.19 |
댓글