DEV Community

Keith
Keith

Posted on • Originally published at Medium

4 3

Java 8 lambda function implements deduplication of lists based on property values

Image description
If your project uses java8, there is a very simple way to deal with the deduplication according to the value of a certain attribute in the list, which is to use lamba function. The example code is as follows:

List<UcShopCourseBizPojo> unique = ucShopCourseBizPojoList.stream().collect(
 collectingAndThen(
 toCollection(() -> new TreeSet<>(comparingLong(UcShopCourseBizPojo::getId))), ArrayList::new));
Enter fullscreen mode Exit fullscreen mode

The comparingLong method is because in the pojo class UcShopCourseBizPojo, the duplication is removed according to the id, and the data type of the id attribute is Long. This method can be replaced by a more general method. The example code is as follows:

List<UcShopCourseBizPojo> sLists = shopCourseLists.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(c -> c.getShopId()))), ArrayList::new)
);
Enter fullscreen mode Exit fullscreen mode

However, this method of filtering weight has a disadvantage, which is, the obtained list may return random results each time, such as obtaining a list of store courses and deduplicating courses with the same shopid. If the shopid of two courses is the same, it may be called every time. Sometimes I will return to this course, and I will return to another course. I don’t know what the underlying cause is. This method is for reference only. If you know the reason, you can leave a message~

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more