Java 8 Distinct by property

后端 未结 29 1872
傲寒
傲寒 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条回答
  •  猫巷女王i
    2020-11-21 22:55

    In my case I needed to control what was the previous element. I then created a stateful Predicate where I controled if the previous element was different from the current element, in that case I kept it.

    public List fetchLogById(Long id) {
        return this.findLogById(id).stream()
            .filter(new LogPredicate())
            .collect(Collectors.toList());
    }
    
    public class LogPredicate implements Predicate {
    
        private Log previous;
    
        public boolean test(Log atual) {
            boolean isDifferent = previouws == null || verifyIfDifferentLog(current, previous);
    
            if (isDifferent) {
                previous = current;
            }
            return isDifferent;
        }
    
        private boolean verifyIfDifferentLog(Log current, Log previous) {
            return !current.getId().equals(previous.getId());
        }
    
    }
    

提交回复
热议问题