简体   繁体   English

在Java中从两个不同的数组列表对象中找到不常见的公共元素

[英]Find the uncommon, common all elements from two different array list objects in java

I am trying to find the uncommon, common items from two different non-ordered array list objects in java. 我正在尝试从java中两个不同的无序数组列表对象中找到不常见的常见项目。 I have already read many posts about these but could not find a proper answer. 我已经阅读了很多关于这些的文章,但是找不到正确的答案。

The first array list objects stores the data that are fetched from the server. 第一个数组列表对象存储从服务器获取的数据。 The second array list objects stores the local database data. 第二个数组列表对象存储本地数据库数据。

Now I am trying to find the common, uncommon all elements from these two array lists. 现在,我试图从这两个数组列表中找到常见的,不常见的所有元素 Here the array lists are generated from completely two different model classes but they have similar properties. 此处,数组列表是从完全两个不同的模型类生成的,但是它们具有相似的属性。

The equal comparison does give the common value but can't find the uncommon items from the two array lists when i put the condition as "!listA.id.equals(listB.id)". 当我将条件设置为“!listA.id.equals(listB.id)”时,相等比较的确给出了公共值,但无法从两个数组列表中找到不常见的项。

For example: 例如:

for(CustomStation user1 : localStationLists) {
                            for(CustomStation user2 : serverStationLists) {
                                if(user1.getStationId().equals(user2.getStationId())) {
                                    *//*if(!user1.getTitle().equals(user2.getTitle())) {
                                        resultList.add(user1);
                                    }*//*
                                    //System.out.println(" EQUAL St ids : " + user1);
                                    resultList.add(user2);
                                }
                                else{
                                    resultList1.add(user1);
                                }
                            }

So, thinking whether you guys are also having the same problems? 那么,想想你们是否也遇到同样的问题?

Have been trying for last three days with different approaches but have been failed repeatedly to get a solution. 最近三天一直在尝试使用不同的方法,但一直未能获得解决方案。

These feel like set operations to me: union, overlap, and difference. 这些感觉对我来说像是固定的操作:并集,重叠和差异。

Have a look at this: 看看这个:

Classical set operations for java.util.Collection java.util.Collection的经典集合操作

Works perfectly for me. 非常适合我。 Here's the code: 这是代码:

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

/**
 * Add something descriptive here.
 * User: mduffy
 * Date: 3/26/2015
 * Time: 1:27 PM
 * @link https://stackoverflow.com/questions/29284061/find-the-uncommon-common-all-elements-from-two-different-array-list-objects-in/29284162?noredirect=1#comment46767251_29284162
 */
public class SetOperationDemo {

    public static void main(String[] args) {
        List<String> setOne = new ArrayList<String>() {{
            add("A");
            add("B");
            add("C");
            add("D");
            add("E");
        }};
        List<String> setTwo = new ArrayList<String>() {{
            add("D");
            add("E");
            add("F");
            add("G");
        }};

        System.out.println("Set A           : " + setOne);
        System.out.println("Set B           : " + setTwo);
        List<String> base = new ArrayList<String>(setOne);
        base.retainAll(setTwo);
        System.out.println("Intersection A+B: " + base);
        base = new ArrayList<String>(setOne);
        base.removeAll(setTwo);
        System.out.println("Subtraction  A-B: " + base);
        base = new ArrayList<String>(setTwo);
        base.removeAll(setOne);
        System.out.println("Subtraction  B-A: " + base);
        base = new ArrayList<String>(setOne);
        base.addAll(setTwo);
        System.out.println("Union A union B : " + base);
    }
}

Here's the output: 这是输出:

Set A           : [A, B, C, D, E]
Set B           : [D, E, F, G]
Intersection A+B: [D, E]
Subtraction  A-B: [A, B, C]
Subtraction  B-A: [F, G]
Union A union B : [A, B, C, D, E, D, E, F, G]

Process finished with exit code 0

If your Lists contain custom classes, you have to be sure that they override equals and hashCode properly or they won't give the expected behavior. 如果您的列表包含自定义类,则必须确保它们正确覆盖了equals和hashCode,否则它们将不会给出预期的行为。 Here's my code using a custom class that shows how it's done. 这是我的代码,使用一个自定义类显示了它的完成方式。

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

/**
 * Add something descriptive here.
 * User: mduffy
 * Date: 3/26/2015
 * Time: 1:27 PM
 * @link https://stackoverflow.com/questions/29284061/find-the-uncommon-common-all-elements-from-two-different-array-list-objects-in/29284162?noredirect=1#comment46767251_29284162
 */
public class SetOperationDemo {

    public static void main(String[] args) {
        List<DemoPerson> setOne = new ArrayList<DemoPerson>() {{
            add(new DemoPerson("Andy", "A"));
            add(new DemoPerson("Bob", "B"));
            add(new DemoPerson("Carl", "C"));
            add(new DemoPerson("David", "D"));
            add(new DemoPerson("Ernie", "E"));
        }};
        List<DemoPerson> setTwo = new ArrayList<DemoPerson>() {{
            add(new DemoPerson("David", "D"));
            add(new DemoPerson("Ernie", "E"));
            add(new DemoPerson("Frank", "F"));
            add(new DemoPerson("Gary", "G"));
        }};

        System.out.println("Set A           : " + setOne);
        System.out.println("Set B           : " + setTwo);
        List<DemoPerson> base = new ArrayList<DemoPerson>(setOne);
        base.retainAll(setTwo);
        System.out.println("Intersection A+B: " + base);
        base = new ArrayList<DemoPerson>(setOne);
        base.removeAll(setTwo);
        System.out.println("Subtraction  A-B: " + base);
        base = new ArrayList<DemoPerson>(setTwo);
        base.removeAll(setOne);
        System.out.println("Subtraction  B-A: " + base);
        base = new ArrayList<DemoPerson>(setOne);
        base.addAll(setTwo);
        System.out.println("Union A union B : " + base);
    }
}

class DemoPerson {
    private final String firstName;
    private final String lastName;

    public DemoPerson(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DemoPerson that = (DemoPerson) o;

        return !(firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) && !(lastName != null ? !lastName.equals(that.lastName) : that.lastName != null);

    }

    @Override
    public int hashCode() {
        int result = firstName != null ? firstName.hashCode() : 0;
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("'").append(firstName).append('\'');
        sb.append(" '").append(lastName).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

And here's the output, still behaving as it should: 这是输出,仍然保持应有的状态:

Set A           : [{'Andy' 'A'}, {'Bob' 'B'}, {'Carl' 'C'}, {'David' 'D'}, {'Ernie' 'E'}]
Set B           : [{'David' 'D'}, {'Ernie' 'E'}, {'Frank' 'F'}, {'Gary' 'G'}]
Intersection A+B: [{'David' 'D'}, {'Ernie' 'E'}]
Subtraction  A-B: [{'Andy' 'A'}, {'Bob' 'B'}, {'Carl' 'C'}]
Subtraction  B-A: [{'Frank' 'F'}, {'Gary' 'G'}]
Union A union B : [{'Andy' 'A'}, {'Bob' 'B'}, {'Carl' 'C'}, {'David' 'D'}, {'Ernie' 'E'}, {'David' 'D'}, {'Ernie' 'E'}, {'Frank' 'F'}, {'Gary' 'G'}]

Process finished with exit code 0

I have not tested this code but you can try this: 我尚未测试此代码,但是您可以尝试以下操作:

for(CustomStation user1 : localStationLists) 
{
    boolean flag = false;
    for(CustomStation user2 : serverStationLists) 
    {
        if(user1.getStationId().equals(user2.getStationId())) 
        {
            if(!user1.getTitle().equals(user2.getTitle())) 
            {
                resultList.add(user1);
            }            
            resultList.add(user2);
            flag = true;
            break;
        }
    }

    if(flag == false)
    {
        resultList1.add(user1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM