Find the difference between two collections in Java 8?

前端 未结 2 1057
慢半拍i
慢半拍i 2021-02-02 11:34

I am trying to make a List of all of the books in one Collection that are not present in another. My problem is that I need to compare based on book ID

2条回答
  •  我在风中等你
    2021-02-02 12:16

    The problem is complex, but it boils down to one thing, know your data. Is it imutables, entities with an id, duplicate entries etc? The code below works for immutables with only values (and with possible duplicates). It first tries to remove all entries in the before list (from the copied after-list). What is left will be the added elements. The ones from the before-list that can be removed from the after-list are the unchanged ones. The rest are the removed ones

    package scrap;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ListDiffer {
    
        private List addedList = new ArrayList<>();
        private List unchangedList = new ArrayList<>();
        private List removedList = new ArrayList<>();
    
        public ListDiffer(List beforeList, List afterList) {
            addedList.addAll(afterList); // Will contain only new elements when all elements in the Before-list are removed.
            beforeList.forEach(e -> {
                boolean b = addedList.remove(e) ? unchangedList.add(e) : removedList.add(e);
            });
        }
    
        public List getAddedList() {
            return addedList;
        }
    
        public List getUnchangedList() {
            return unchangedList;
        }
    
        public List getRemovedList() {
            return removedList;
        }
    }
    

提交回复
热议问题