본문 바로가기
  • 오늘도 한걸음. 수고많았어요.^^
  • 조금씩 꾸준히 오래 가자.ㅎ
IT기술/JAVA

[Java] Stream filter 예시

by 미노드 2024. 2. 26.

filter는 자주 사용하는 기능 중 하나입니다.

간단한 예시를 통해 이해해봅시다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Stream Filter 필터 예제
public class FilterEx {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("가가""나나""다다""나나""라라");
 
 
        names.stream()
                .filter(n -> n.startsWith("가"))
                .forEach(n -> System.out.println(n)); // 가로 시작된것만 가져오기
        System.out.println("-----");
 
        names.stream()
                .filter(n -> {
                    if (n.contains("나") ) return true// true 반환 이라면 결과에 포함시킴.
                    else return false// false반환 이라면 결과에 포함 시키지 않음.
                })
                .forEach(n -> System.out.println(n)); //
        System.out.println("-----");
 
        names.stream()
                .distinct()
                .filter(n -> n.startsWith("다"))
                .filter(n -> n.startsWith("나"))
                .forEach(n -> System.out.println(n)); // 다, 나로 시작된것만 가져오기, 없음
    }
}
 
cs

필터에 조건을 추가해서 true 라면 포함, false라면 포함시키지 않습니다.

이후 마지막 조건으로 forEach로 반복시켜 출력할 수 있습니다.

1
2
3
4
5
6
7
8
List<String> result = names.stream()
                .filter(n -> {
                    if (n.contains("나")) return true// true 반환 이라면 결과에 포함시킴.
                    else return false// false반환 이라면 결과에 포함 시키지 않음.
                })
                .toList();//
//                .collect(Collectors.toList());
        System.out.println("List  : "+result);
cs

뿐만 아니라 List로 변환해서 출력도 가능합니다. stream 이 지원하는 결과로 여러 컬랙션으로 출력가능