Java 比较 2 个 ArrayLists 的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19155283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:34:36  来源:igfitidea点击:

Simple way to compare 2 ArrayLists

javalistarraylist

提问by prabu

I have 2 arraylists of string object.

我有 2 个字符串对象的数组列表。

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.

我的预期输出是 2 ArrayList of string,其中第一个列表应该从源中删除所有字符串,第二个列表应该将所有字符串新添加到源中。

Any simpler method to achieve this?

有没有更简单的方法来实现这一目标?

采纳答案by Maxim Shoustin

Convert Lists to Collectionand use removeAll

将列表转换为 Collection并使用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]

回答by Micha?l Benjamin Saerens

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

据我理解正确,我认为使用 4 个列表最容易: - 你的 sourceList - 你的 destinationList - A removedItemsList - A newAddedItemsList

回答by Husman

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.

这应该检查两个列表是否相等,它首先进行一些基本检查(即空值和长度),然后排序并使用 collections.equals 方法检查它们是否相等。

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

回答by Ishan Rastogi

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.

虽然如果您的源列表和目标列表有很多元素,它可能不是很有效,但肯定会更简单。

回答by Rakesh KR

Convert the Listin to Stringand check whether the Strings are same or not

Listin转换为String并检查字符串是否相同

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

回答by Sumit Ramteke

The answer is given in @dku-rajkumarpost.

答案在@dku-rajkumar帖子中给出。

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

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

回答by Aniruddha

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

回答by Nitin Chand

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.

这将返回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.

由于排序不同,将返回 false。

回答by Nikhil

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