Java 8 Distinct by property

后端 未结 29 2270
傲寒
傲寒 2020-11-21 22:35

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of

29条回答
  •  轮回少年
    2020-11-21 22:58

    You can wrap the person objects into another class, that only compares the names of the persons. Afterward, you unwrap the wrapped objects to get a person stream again. The stream operations might look as follows:

    persons.stream()
        .map(Wrapper::new)
        .distinct()
        .map(Wrapper::unwrap)
        ...;
    

    The class Wrapper might look as follows:

    class Wrapper {
        private final Person person;
        public Wrapper(Person person) {
            this.person = person;
        }
        public Person unwrap() {
            return person;
        }
        public boolean equals(Object other) {
            if (other instanceof Wrapper) {
                return ((Wrapper) other).person.getName().equals(person.getName());
            } else {
                return false;
            }
        }
        public int hashCode() {
            return person.getName().hashCode();
        }
    }
    

提交回复
热议问题