Find the difference between two collections in Java 8?

前端 未结 2 1022
慢半拍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<T> {
    
        private List<T> addedList = new ArrayList<>();
        private List<T> unchangedList = new ArrayList<>();
        private List<T> removedList = new ArrayList<>();
    
        public ListDiffer(List<T> beforeList, List<T> 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<T> getAddedList() {
            return addedList;
        }
    
        public List<T> getUnchangedList() {
            return unchangedList;
        }
    
        public List<T> getRemovedList() {
            return removedList;
        }
    }
    
    0 讨论(0)
  • 2021-02-02 12:23
    List<Book> books1 = ...;
    List<Book> books2 = ...;
    Set<Integer> ids = books2.stream()
            .map(Book::getId)
            .collect(Collectors.toSet());
    List<Book> parentBooks = books1.stream()
            .filter(book -> !ids.contains(book.getId()))
            .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题