Compare 2 lists and remove duplicates java 8
Ngày đăng:
07/12/2021
Trả lời:
0
Lượt xem:
79
Remove duplicates from a list of objects based on property in Java 8You can get a stream from the List and put in in the TreeSet from which you provide a custom comparator that compares id uniquely. Then if you really need a list you can put then back this collection into an ArrayList. import static java.util.Comparator.comparingInt; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; ... ListGiven the example: It will output: [Employee{id=1, name='John'}, Employee{id=2, name='Alice'}]Another idea could be to use a wrapper that wraps an employee and have the equals and hashcode method based with its id: class WrapperEmployee { private Employee e; public WrapperEmployee(Employee e) { this.e = e; } public Employee unwrap() { return this.e; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WrapperEmployee that = (WrapperEmployee) o; return Objects.equals(e.getId(), that.e.getId()); } @Override public int hashCode() { return Objects.hash(e.getId()); } }Then you wrap each instance, call distinct(), unwrap them and collect the result in a list. In fact, I think you can make this wrapper generic by providing a function that will do the comparison: public class Wrapperand the mapping will be: .map(e -> new Wrapper<>(e, Employee::getId))The easiest way to do it directly in the list is |