본문

170420(목) - Streams <Terminal Operations>

Streams


- Matching

- At least one element matches to the predicate


  1. //Check if at least one student has got distinction
  2. Boolean hasStudentWithDistinction = students.stream()
  3. .anyMatch(student -> student.getScore() > 80);



     - All element match to the predicate


  1. //Check if All of the students have distinction
  2. Boolean hasAllStudentsWithDistinction = students.stream()
  3. .allMatch(student -> student.getScore() > 80);



- None of the elements matches to the predicate


  1. //Return true if None of the students are over distinction
  2. Boolean hasAllStudentsBelowDistinction = students.stream()
  3. .noneMatch(student -> student.getScore() > 80);



- Finding


  1. //Returns any student that matches to the given condition
  2. students.stream().filter(student -> student.getAge() > 20)
  3. .findAny();
  4. //Returns first student that matches to the given condition
  5. students.stream().filter(student -> student.getAge() > 20)
  6. .findFirst();



- Reducing

ㆍ하나의 element 형태로 출력을 생성하기 위해서 streams내의 element를 반복하여 처리

ㆍ모든 요소의 합, 최대 최소 element 계산 등에 유리

ㆍ함수형 언어의 fold 개념과 비슷하다.


- Summing and Multiplying


  1. //Summing all elements of a stream
  2. Integer sum = numbers.stream()
  3. .reduce(0, (x, y) -> x + y); //reduce(identity, accumulator)


  1. //Product of all elements in a stream
  2. Integer product = numbers.stream()
  3. .reduce(1, (x, y) -> x * y);


  1. //Summing without passing an identity
  2. Optional<integer> sum = numbers.stream()
  3. .reduce((x, y) -> x + y);
  4. //Product without passing an identity
  5. Optional<integer> product = numbers.stream()
  6. .reduce((x, y) -> x * y);



- Min and Max


  1. //Min of the stream
  2. Optional<integer> min = numbers.stream()
  3. .reduce(0, Integer::min);
  4. //Max of the stream
  5. Optional<integer> max = numbers.stream()
  6. .reduce(0, Integer::max);



- Optional

ㆍ객체가 할당되었는지, 할당 해제되었는지 나타냄 : Null 반환에 대한 대비책

ㆍfindAny() 에서 Optional  반환 -> map은 Optional instance에서 호출된다.


  1. students.stream()
  2. .filter(student -> student.getScore() > 80) // filter
  3. .findAny() //Any student matching to the filter
  4. .map(Student::getName) // mapping to students name
  5. .ifPresent(System.out::println); // print if name of the student is not Null



공유

댓글