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 이 지원하는 결과로 여러 컬랙션으로 출력가능
'IT기술 > JAVA' 카테고리의 다른 글
[JAVA] 객체지향 설계 5원칙 SOLID 원칙 (0) | 2024.02.08 |
---|---|
[java] assert 개발 테스트 에서 조건 걸기 (0) | 2024.02.03 |
[Java] string 시작문자로 시작되는지, 끝문자로 끝나는지 확인하기 체크하기 (0) | 2024.01.24 |
[Java] null 에 대한 검증, 처리방법 (0) | 2024.01.14 |
[Java] 자바에서 싱글톤 패턴 이해하기 (0) | 2024.01.13 |