Friday, 9 February 2018

Removing duplicates by field/property in Java 8

How to remove duplicates in Java 8 using field or property ? We might use reduce!
List<MyClass> distinctByField = myList.stream().reduce(new ArrayList<>(), (List<MyClass> accumulator, MyClass myClass) -> {
    if (accumulator.stream().noneMatch(item -> item.getField().equals(myClass.getField()))) {
        accumulator.add(MyClass);
    }
    return accumulator;
}, (acc1, acc2) -> {
    acc1.addAll(acc2);
    return acc1;
});

No comments:

Post a Comment