比較集合

凛冬雪夜發表於2024-11-09
點選檢視程式碼

import lombok.Getter;

import java.util.*;
import java.util.stream.Collectors;

public class CollectionUtils {

    /**
     * compare
     * @param newCollection 新集合 
     * @param oldCollection 舊集合 
     * @param comparator    
     * @param <T>
     * @return
     */
    public static <T> CompareResult<T> compare(List<T> newCollection, List<T> oldCollection, Comparator<T> comparator) {
        List<T> existNewElements = new ArrayList<>();
        List<T> existOldElements = new ArrayList<>();
        Iterator<T> newIterator = newCollection.iterator();
        while (newIterator.hasNext()) {
            T newObj = newIterator.next();
            Iterator<T> oldIterator = oldCollection.iterator();
            while (oldIterator.hasNext()) {
                T oldObj = oldIterator.next();
                if (comparator.compare(newObj, oldObj) == 0) {
                    existNewElements.add(newObj);
                    existOldElements.add(oldObj);
                    try {
                        oldIterator.remove();
                        newIterator.remove();
                    } catch (UnsupportedOperationException e) {
                        throw new RuntimeException("");
                    }
                }
            }
        }
        return new CompareResult<T>(newCollection, oldCollection, existNewElements, existOldElements);
    }

    @Getter
    public static class CompareResult<T> {
      
        private final List<T> addElements;
       
        private final List<T> deleteElements;
        
        private final List<T> existNewElements;
        
        private final List<T> existOldElements;

        public CompareResult(List<T> addElements, List<T> delValue, List<T> existNewElements, List<T> existOldElements) {
            this.addElements = addElements;
            this.deleteElements = delValue;
            this.existNewElements = existNewElements;
            this.existOldElements = existOldElements;
        }
    }

    public static void main(String[] args) {
       
        List<User> newCollection = new ArrayList<>(Arrays.asList(user2_new, user3));
        List<User> oldCollection = new ArrayList<>(Arrays.asList(user1, user2));

        System.out.println("newCollection:    " + newCollection);
        System.out.println("oldCollection:    " + oldCollection);

        CompareResult<User> compareResult = compare(newCollection, oldCollection, (o1, o2) -> {
            if (o1.getId().equals(o2.getId())) {
                return 0;
            } else {
                return -1;
            }
        });

        System.err.println("addElements:      " + compareResult.getAddElements());
        System.err.println("deleteElements:   " + compareResult.getDeleteElements());
        System.err.println("existNewElements: " + compareResult.getExistNewElements());
        System.err.println("existOldElements: " + compareResult.getExistOldElements());
    }
}

相關文章