본문

170420(목) - Streams <Intermediate Operations>

Streams 


- Mapping

ㆍelements의 형태를 변경하는 process

ㆍsql 에서의 select 방식이라고 생각하면 된다.


- map

ㆍstreams element 변경이나 형식 변경에 사용

ㆍ다른 함수를 인수로 취한다.


  1. students.stream()
  2. .map(Student::getName)
  3. .forEach(System.out::println);



- FlatMap

ㆍmap과 별도로 새로 형성된 element의 하위 Stream을 생성

ㆍ마지막에 모든 하위 steam을 단일 steam으로 변경


  1. List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
  2. List<List<Integer>> mapped =
  3. numbers.stream()
  4. .map(number -> Arrays.asList(number -1, number, number +1))
  5. .collect(Collectors.toList());
  6. System.out.println(mapped); //:> [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
  7. List<Integer> flattened =
  8. numbers.stream()
  9. .flatMap(number -> Arrays.asList(number -1, number, number +1).stream())
  10. .collect(Collectors.toList());
  11. System.out.println(flattened); //:> [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5]




- Filtering

- filter

ㆍpredicate를 인수로 사용함


  1. //Only the students with score >= 60
  2. students.stream()
  3. .filter(student -> student.getScore() >= 60)
  4. .collect(Collectors.toList());



- Unique Elements

ㆍ중복 요소 제거


  1. //Get distinct list of names of the students
  2. students.stream()
  3. .map(Student::getName)
  4. .distinct()
  5. .collect(Collectors.toList());



- Limiting

ㆍ조건이 만족되면 나머지는 short circuit에 의해서 skip 된다.


  1. //List of first 3 students who have age > 20
  2. students.stream()
  3. .filter(s -> s.getAge() > 20)
  4. .map(Student::getName)
  5. .limit(3)
  6. .collect(Collectors.toList());



- Skipping

ㆍ스킵되는 수가 element 보다 많으면 빈값이 리턴된다.


  1. //List of all the students who have age > 20 except the first 3
  2. students.stream()
  3. .filter(s -> s.getAge() > 20)
  4. .map(Student::getName)
  5. .skip(3)
  6. .collect(Collectors.toList());



- Sorting


  1. students.stream()
  2. .map(Student::getName)
  3. .sorted()
  4. .collect(Collectors.toList());



  1. students.stream()
  2. .sorted(Comparator.comparing(Student::getName))
  3. .map(Student::getName)
  4. .collect(Collectors.toList());



  1. //Sorting names if the Students in descending order
  2. students.stream()
  3. .map(Student::getName)
  4. .sorted(Comparator.reverseOrder())
  5. .collect(Collectors.toList());
  6. //Sorting names if the Students in descending order
  7. students.stream()
  8. .map(Student::getName)
  9. .sorted(Comparator.reverseOrder())
  10. .collect(Collectors.toList());
  11. //Sorting students by First Name and Last Name both
  12. students.stream()
  13. .sorted(Comparator.comparing(Student::getFirstName).
  14. thenComparing(Student::getLastName))
  15. .map(Student::getName)
  16. .collect(Collectors.toList());
  17. //Sorting students by First Name Descending and Last Name Ascending
  18. students.stream()
  19. .sorted(Comparator.comparing(Student::getFirstName)
  20. .reversed()
  21. .thenComparing(Student::getLastName))
  22. .map(Student::getName)
  23. .collect(Collectors.toList());


공유

댓글