본문 바로가기

(Java) steam + filter 중복 객체 제거

2021. 3. 23.

필터할 객체의 형태

객체 내부의 요소를 이용해 필터 할 것이다.

  • Node로 이루어진 List에서 Node 객체의 x 요소가 중복이 된다면 필터링 할 예정
class Node {
    private int x;
    private int y;

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public String toString() {
        return "Node{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
public static void main(String[] args) {

        List<Node> list = new ArrayList<>();
        Set<Integer> s = new HashSet<>();

        list.add(new Node(1, 2));
        list.add(new Node(1, 3));
        list.add(new Node(2, 2));

        list = list.stream().filter(a -> {
            if(!s.contains(a.getX())){
                s.add(a.getX());
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        for (Node o : list)
            System.out.println(o);
    }

    /*
    출력 결과
    Node{x=1, y=2}
    Node{x=2, y=2}

    */
  • filter를 이용해 리스트의 담긴 node 하나씩 가져올 수 있다.
  • node의 각요소를 참조하여 필터링을 할 경우 대괄호로 묶어 return 값을 지정한다.
  • 필터링 결과를 collector로 리스트를 만들어준다.

'Java' 카테고리의 다른 글

(Java) 클래스, 객체, 인스턴스  (0) 2021.03.11
(Java) Comparable과 Comparator 개념  (0) 2020.12.16
댓글