Simple way to compare 2 ArrayLists

与世无争的帅哥 提交于 2019-11-26 10:35:16

问题


I have 2 arraylists of string object.

List<String> sourceList = new ArrayList<String>();
List<String> destinationList = new ArrayList<String>();

I have some logic where i need to process the source list and will end up with the destination list. The destination list will have some additional elements added to the source list or removed from source list.

My expected output is 2 ArrayList of string where the first list should have all the strings removed from the source and second list should have all the strings newly added to the source.

Any simpler method to achieve this?


回答1:


Convert Lists to Collection and use removeAll

    Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
    Collection<String> listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));


    List<String> sourceList = new ArrayList<String>(listOne);
    List<String> destinationList = new ArrayList<String>(listTwo);


    sourceList.removeAll( listTwo );
    destinationList.removeAll( listOne );



    System.out.println( sourceList );
    System.out.println( destinationList );

Output:

[c, g]
[gg, h]

[EDIT]

other way (more clear)

  Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));

    List<String> sourceList = new ArrayList<String>(list);
    List<String> destinationList = new ArrayList<String>(list);

    list.add("boo");
    list.remove("b");

    sourceList.removeAll( list );
    list.removeAll( destinationList );


    System.out.println( sourceList );
    System.out.println( list );

Output:

[b]
[boo]



回答2:


This should check if two lists are equal, it does some basic checks first (i.e. nulls and lengths), then sorts and uses the collections.equals method to check if they are equal.

public  boolean equalLists(List<String> a, List<String> b){     
    // Check for sizes and nulls

    if (a == null && b == null) return true;


    if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size()))
    {
        return false;
    }

    // Sort and compare the two lists          
    Collections.sort(a);
    Collections.sort(b);      
    return a.equals(b);
}



回答3:


Convert the List in to String and check whether the Strings are same or not

import java.util.ArrayList;
import java.util.List;



/**
 * @author Rakesh KR
 *
 */
public class ListCompare {

    public static boolean compareList(List ls1,List ls2){
        return ls1.toString().contentEquals(ls2.toString())?true:false;
    }
    public static void main(String[] args) {

        ArrayList<String> one  = new ArrayList<String>();
        ArrayList<String> two  = new ArrayList<String>();

        one.add("one");
        one.add("two");
        one.add("six");

        two.add("one");
        two.add("two");
        two.add("six");

        System.out.println("Output1 :: "+compareList(one,two));

        two.add("ten");

        System.out.println("Output2 :: "+compareList(one,two));
    }
}



回答4:


The answer is given in @dku-rajkumar post.

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




回答5:


If your requirement is to maintain the insertion order plus check the contents of the two arraylist then you should do following:

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

listOne.add("stack");
listOne.add("overflow");

listTwo.add("stack");
listTwo.add("overflow");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

This will return true.

However, if you change the ordering for example:

listOne.add("stack");
listOne.add("overflow");

listTwo.add("overflow");
listTwo.add("stack");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

will return false as ordering is different.




回答6:


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.




回答7:


boolean isEquals(List<String> firstList, List<String> secondList){
    ArrayList<String> commons = new ArrayList<>();

    for (String s2 : secondList) {
        for (String s1 : firstList) {
           if(s2.contains(s1)){
               commons.add(s2);
           }
        }
    }

    firstList.removeAll(commons);
    secondList.removeAll(commons);
    return !(firstList.size() > 0 || secondList.size() > 0) ;
}



回答8:


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




回答9:


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();
}


来源:https://stackoverflow.com/questions/19155283/simple-way-to-compare-2-arraylists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!