woniper

java8 stream match 본문

Java

java8 stream match

woniper1 2016. 12. 3. 22:28
  두 리스트를 비교해 데이터를 추출해야되는 요구사항이 있다. 보통 Collection을 사용한 로직은 반복문을 사용해야하는데, 2개의 리스트가 있는 경우는 2중 for문을 사용하는게 대부분이다.
  java8 stream에서는 어떻게 2중 for문을 사용할지, 어떻게 데이터를 필터링하는지 알아보자.


대상 리스트

1
2
private List<String> targetList = Arrays.asList("a""b""c""d""e");
private List<String> filterList = Arrays.asList("a""b");
cs


불일치 데이터 필터링

1
2
3
4
5
6
7
8
9
@Test
public void testTwoListNonMatch() throws Exception {
    List<String> filteredList = targetList.stream()
          .filter(target -> filterList.stream().noneMatch(Predicate.isEqual(target)))
          .collect(Collectors.toList());
 
    System.out.println(filteredList);  // [c, d, e]
    assertTrue(filteredList.size() == 3);
}
cs

  4라인에 nonMatch 메소드를 주목하자.

targetList와 filterList를 비교해 불일치(noneMatch)하는 데이터를 기준으로 filter 메소드를 실행했다.

c, d, e가 출력된다.


일치 데이터 필터링

1
2
3
4
5
6
7
8
9
@Test
public void testTwoListAnyMatch() throws Exception {
    List<String> filteredList = targetList.stream()
            .filter(target -> filterList.stream().anyMatch(Predicate.isEqual(target)))
            .collect(Collectors.toList());
 
    System.out.println(filteredList);   // [a, b]
    assertTrue(filteredList.size() == 2);
}
cs

  이번에 사용된 메소드는 anyMatch 메소드다. 

targetList와 filterList를 비교해 일치하는(anyMatch) 데이터를 기준으로 filter 메소드를 실행했다.

a, b가 출력된다.


모두 일치하는 데이터 필터링

1
2
3
4
5
6
7
8
9
@Test
public void testTwoListAllMatch() throws Exception {
    List<String> filteredList = targetList.stream()
            .filter(target -> filterList.stream().allMatch(Predicate.isEqual(target)))
            .collect(Collectors.toList());
 
    System.out.println(filteredList);   // []
    assertTrue(filteredList.size() == 0);
}
cs

  allMatch라는 메소드가 있다. 조금 헷갈린다. 모든 데이터가 일치해야만 한다. 그런데 allMatch는 String List로 예제는 조금 불명확한 예제인것 같다.


Integer List 예제를 보자.
1
2
3
4
5
@Test
public void allMatch() throws Exception {
    List<Integer> targetList = Arrays.asList(12345);
    assertTrue(targetList.stream().allMatch(n -> n < 6));
}
cs

  allMatch 조건이 6미만이다. 즉 조건에 모든 데이터가 만족해야만 true를 반환한다.

Comments