기록 - 프로그래밍/Java
[Stream] Match method
wjjun
2020. 7. 28. 06:22
match
특정 요소를 포함하고 있는지 확인하기 위해 사용합니다
match method 3가지
boolean anyMatch(Predicate<? super T> predicate);
boolean allMatch(Predicate<? super T> predicate);
boolean noneMatch(Predicate<? super T> predicate);
공통 소스
private List<Student> students;
@Before
public void anyMatch(){
students = new ArrayList<>();
students.add(new Student("hun", 20, "Literature"));
students.add(new Student("kim", 21, "Literature"));
students.add(new Student("joe", 22, "science"));
students.add(new Student("sara", 20, "science"));
}
1. anyMatch()
최소 하나의 요소가 포함되어 있다면 반환 값은 true 입니다.
최소 하나의 요소도 포함되어 있지 않다면 반환 값은 false 입니다.
스트림이 비어 있어도 반환 값은 false 입니다.
@Test
public void testAnyMatch(){
boolean anyAdultCourseStudents = students.stream()
.anyMatch(s -> s.getCourse().equals("science"));
System.out.println("anyAdultDayStudents is " + anyAdultCourseStudents);
}
---출력결과---
anyAdultDayStudents is true
2. allMatch()
모든 요소가 동일하다면 반환 값은 true 입니다.
스트림이 비어 있다면 반환 값은 true 입니다.
하나의 요소라도 다르다면 반환 값은 false 입니다.
@Test
public void testAllMatch(){
boolean allMatchCourseStudents = students.stream()
.allMatch(s -> s.getCourse().equals("science"));
System.out.println("allMatchCourseStudents is " + allMatchCourseStudents );
}
---출력결과---
allMatchCourseStudents is false
3. noneMatch()
특정 요소와 일치하는 요소가 존재하지 않으면 반환 값은 true 입니다.
스트림이 비어 있다면 반환 값은 true 입니다.
하나의 요소라도 일치한다면 반환 값은 false 입니다.
@Test
public void noneMatch(){
boolean noneMatchCourse = students.stream()
.noneMatch(s -> s.getCourse().equals("science"));
System.out.println("noneMatchCourse is " + noneMatchCourse);
noneMatchCourse = students.stream()
.noneMatch(s -> s.getCourse().equals("korean"));
System.out.println("noneMatchCourse is " + noneMatchCourse);
}
---출력결과---
noneMatchCourse is false
noneMatchCourse is true