스트림 필터링

스트림에서 지원하는 filter 메서드 사용.

프리디케이트를 인수로 받아서 프레디케이트와 일치하는 모든 요소를 포함하는 스트림을 반환.

List<Integer> numArr = Arrays.asList(1,2,1,3,3,3,2,4,5);
numArr.stream()
	.filter(i -> i == 3)
	.forEach(System.out::println);

 

요소 중에 3인 요소들이 있으면 출력.

여기서 중복을 제거하는 고유 요소 필터링을 하고 싶다면 스트림에서 지원하는 distinct 메서드를 사용한다.

고유 여부는 스트림에서 만든 객체의 hashcode, equals로 결정.

List<Integer> numArr = Arrays.asList(1,2,1,3,3,3,2,4,5);
numArr.stream()
	.filter(i -> i == 3)
	.distinct()
	.forEach(System.out::println);

 

스트림 슬라이싱

프리디케이트를 이용한 슬라이싱, 스트림 요소 무시, 축소 등 다양한 방법으로 요소를 선택하거나 스킵할 수 있다.

아래 예제는 단순히 게임 목록에 대한 가격 필터링을 한 예제이다.

List<Game> games = Arrays.asList(
	new Game("CALL 1", 20000)
	, new Game("DIA 1", 30000)
	, new Game("DIA 2", 40000)
	, new Game("DIA 3", 50000)
);
List<Game> filteredGame = games.stream()
			.filter(game -> game.getPrice() < 40000)
			.collect(toList());

만약 filter 메서드의 요소를 만족했을 때 작업을 중단하고 싶다면 takeWhile, dropWhile을 사용하면 된다.

사용하지 않는 경우 모든 요소만큼 작업을 수행하므로 요소 목록 크기가 크다면 그만큼 낭비가 된다.

 

takewhile 메서드

프레디케이트가 처음으로 참이 되는 지점까지 발견된 요소를 반환.

List<Game> takeWhileGame = games.stream()
		.takeWhile(game -> game.getPrice() < 40000)
		.collect(toList());

 

dropwhile 메서드

프레디케이트가 처음으로 거짓이 되는 지점까지 발견된 요소를 버림.

List<Game> dropWhileGame = games.stream()
		.dropWhile(game -> game.getPrice() < 40000)
		.collect(toList());

 

limit 메서드

주어진 값 이하의 크기를 갖는 새로운 스트림을 반환.

List<Game> dropWhileGame = games.stream()
		.dropWhile(game -> game.getPrice() < 40000)
       		.limit(1)
		.collect(toList());

 

skip 메서드

처음 N개 요소를 제외한 스트림을 반환.

List<Game> dropWhileGame = games.stream()
		.dropWhile(game -> game.getPrice() < 40000)
       		.skip(2)
		.collect(toList());


위에서 작성한 예제들의 요소 값들을 출력해보면 어떻게 동작하는지 짐작할 수 있습니다.

filteredGame.stream().forEach(game -> System.out.println(game.getName()));
Sytem.out.println();
takeWhileGame.stream().forEach(game -> System.out.println(game.getName()));
Sytem.out.println();
dropWhileGame.stream().forEach(game -> System.out.println(game.getName()));

 

결과 값

CALL 1
DIA 1

CALL 1

DIA 1

 

'Java > Stream' 카테고리의 다른 글

기본형 특화 스트림  (0) 2022.10.27
리듀싱  (0) 2022.10.26
검색과 매칭  (0) 2022.10.26
map과 flatMap  (0) 2022.10.17
정의 및 특징  (0) 2022.10.03

+ Recent posts