Java/Code snippet

[Java] 예제로 이해하기, anyMatch() 및 Stream() 활용

i5 2022. 4. 28. 21:39
반응형

소스코드

package set;

import java.util.HashSet;
import java.util.Set;

public class set_test {

	public static void main(String[] args) {
		// Hashset 선언
		Set<Integer> s = new HashSet<Integer>();
		
		s.add(1);
		s.add(2);
		
		s.add(4);
		s.add(8);
		s.add(16);
		
		// a -> a == 1 이란 뜻은, a라는 임시변수를 선언하고, 해당 set에 대해서, a == 1가 일치하는 요소가 있으면
		// true를 리턴
		System.out.println("s.stream() : " + s.stream().anyMatch(a -> a == 1));
		System.out.println("s.stream() : " + s.stream().anyMatch(a -> a == 2));
		System.out.println("s.stream() : " + s.stream().anyMatch(a -> a == 3));
		System.out.println("s.stream() : " + s.stream().anyMatch(a -> a == 5));
		
		// allMatch() 모든 요소들이 매개값(Predicate)으로 주어진 조건을 만족하는지 조사
		// anyMatch() 최소한 한 개의 요소가 주어진 조건에 만족하는지 조사
		// noneMatch() 모든 요소들이 주어진 조건을 만족하지 않는지 조사
	}
}

 

 

결과화면

s.stream() : true
s.stream() : true
s.stream() : false
s.stream() : false

반응형