Simple way to compare 2 ArrayLists

后端 未结 10 1830
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 00:50

I have 2 arraylists of string object.

List sourceList = new ArrayList();
List destinationList = new ArrayList

        
相关标签:
10条回答
  • 2020-11-30 01:21
    private int compareLists(List<String> list1, List<String> list2){
        Collections.sort(list1);
        Collections.sort(list2);
    
        int maxIteration = 0;
        if(list1.size() == list2.size() || list1.size() < list2.size()){
            maxIteration = list1.size();
        } else {
            maxIteration = list2.size();
        }
    
        for (int index = 0; index < maxIteration; index++) {
            int result = list1.get(index).compareTo(list2.get(index));
            if (result == 0) {
                continue;
            } else {
                return result;
            }
        }
        return list1.size() - list2.size();
    }
    
    0 讨论(0)
  • 2020-11-30 01:22

    As far as I understand it correctly, I think it's easiest to work with 4 lists: - Your sourceList - Your destinationList - A removedItemsList - A newlyAddedItemsList

    0 讨论(0)
  • 2020-11-30 01:24

    The answer is given in @dku-rajkumar post.

    ArrayList commonList = CollectionUtils.retainAll(list1,list2);

    0 讨论(0)
  • 2020-11-30 01:25

    The simplest way is to iterate through source and destination lists one by one like this:

    List<String> newAddedElementsList = new ArrayList<String>();
    List<String> removedElementsList = new ArrayList<String>();
    for(String ele : sourceList){
        if(destinationList.contains(ele)){
            continue;
        }else{
            removedElementsList.add(ele);
        }
    }
    for(String ele : destinationList){
        if(sourceList.contains(ele)){
            continue;
        }else{
            newAddedElementsList.add(ele);
        }
    }
    

    Though it might not be very efficient if your source and destination lists have many elements but surely its simpler.

    0 讨论(0)
提交回复
热议问题