DEV Community

Keith
Keith

Posted on • Originally published at Medium

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~

Top comments (0)