예제가 포함된 Java의 스트림 필터()
스트림 필터(Predicate predicate) 주어진 조건과 일치하는 이 스트림의 요소로 구성된 스트림을 반환합니다. 이것은 중간 작업. 이러한 작업은 항상 게으르다. 즉, filter()와 같은 중간 작업을 실행하면 실제로 필터링이 수행되지 않지만 대신 탐색할 때 주어진 조건과 일치하는 초기 스트림의 요소를 포함하는 새 스트림이 생성됩니다.
통사론:
Stream filter(Predicate predicate)
여기서 Stream은 인터페이스이고 T는 조건자에 대한 입력 유형입니다.
반환 유형: 새로운 스트림.
구현:
- 0에서 10 사이의 특정 숫자로 나눌 수 있는 요소를 필터링합니다.
- 특정 인덱스에서 대문자로 요소를 필터링합니다.
- 사용자 정의 알파벳 문자로 끝나는 요소를 필터링합니다.
예시 1: filter() 메서드를 사용하여 5로 나눌 수 있는 요소를 필터링합니다.
자바
// Java Program to get a Stream Consisting of the Elements> // of Stream that Matches Given Predicate for Stream filter> // (Predicate predicate)> > // Importing required classes> import> java.util.*;> > // Class> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > > // Creating a list of Integers> > List list = Arrays.asList(> 3> ,> 4> ,> 6> ,> 12> ,> 20> );> > > // Getting a stream consisting of the> > // elements that are divisible by 5> > // Using Stream filter(Predicate predicate)> > list.stream()> > .filter(num ->숫자 %> 5> ==> 0> )> > .forEach(System.out::println);> > }> }> |
산출
20
예시 2: index 1에서 대문자로 요소를 필터링하는 작업을 사용하는 filter() 메서드
자바
// Java Program to Get Stream Consisting of Elements> // of Stream that Matches Given Predicate> // for Stream Filter (Predicate predicate)> > // Importing required classes> import> java.util.stream.Stream;> > // Class> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Creating a stream of strings> > Stream stream = Stream.of(> > 'Geeks'> ,> 'fOr'> ,> 'GEEKSQUIZ'> ,> 'techcodeview.com'> );> > > // Getting a stream consisting of the> > // elements having UpperCase Character> > // at custom index say be it '1'> > // using Stream filter(Predicate predicate)> > stream> > .filter(> > str ->Character.isUpperCase(str.charAt(> 1> )))> > .forEach(System.out::println);> > }> }> |
산출
fOr GEEKSQUIZ
예시 3: filter() 메서드는 사용자 정의 알파벳 문자로 끝나는 요소를 필터링하여 구현 목적으로 's'라고 말합니다.
자바
// Java Program to Get a Stream Consisting ofElements> // of Stream that Matches Given predicate> // for Stream filter (Predicate predicate)> > // Importing required classes> import> java.util.stream.Stream;> > // Class> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > > // Creating a stream of strings> > Stream stream = Stream.of(> > 'Geeks'> ,> 'foR'> ,> 'GeEksQuiz'> ,> 'techcodeview.com'> );> > > // Getting a stream consisting of the> > // elements ending with 's'> > // using Stream filter(Predicate predicate)> > stream.filter(str ->str.endsWith(> 's'> ))> > .forEach(System.out::println);> > }> }> |
산출
Geeks techcodeview.com