logo

자바 스트림 필터

Java 스트림은 주어진 조건에 기초하여 스트림 요소를 필터링하는 filter() 메소드를 제공합니다. 목록의 짝수 요소만 가져오고 싶다고 가정하면 필터 메서드를 사용하여 쉽게 이 작업을 수행할 수 있습니다.

이 메소드는 조건자를 인수로 사용하고 결과 요소로 구성된 스트림을 반환합니다.


서명

Stream filter() 메서드의 서명은 다음과 같습니다.

 Stream filter(Predicate predicate) 

매개변수

술부: 인수로 조건자 참조를 사용합니다. 술어는 기능적 인터페이스입니다. 따라서 여기서 람다 식을 전달할 수도 있습니다.

반품

새로운 스트림을 반환합니다.


Java 스트림 필터() 예

다음 예에서는 필터링된 데이터를 가져오고 반복합니다.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); productsList.stream() .filter(p ->p.price> 30000) // filtering price .map(pm ->pm.price) // fetching price .forEach(System.out::println); // iterating price } } 

산출:

 90000.0 

Java 스트림 필터() 예제 2

다음 예에서는 필터링된 데이터를 목록으로 가져옵니다.

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List pricesList = productsList.stream() .filter(p ->p.price> 30000) // filtering price .map(pm ->pm.price) // fetching price .collect(Collectors.toList()); System.out.println(pricesList); } } 

산출:

 [90000.0]