安卓 : Compare two ArrayList of objects and find unmatching ids from the second ArrayList

标签 android object arraylist compare pojo

我想比较两个对象的 ArrayList,并根据对象中的 id 从第二个 ArrayList 中找到不匹配的值。

例如:

Person.java

private int id;
private String name;
private String place;

主要 Activity .java:

ArrayList<Person> arrayList1 = new ArrayList<Person>();
arrayList1.add(new Person(1,"name","place"));
arrayList1.add(new Person(2,"name","place"));
arrayList1.add(new Person(3,"name","place"));

ArrayList<Person> arrayList2 = new ArrayList<Person>();
arrayList2.add(new Person(1,"name","place"));
arrayList2.add(new Person(3,"name","place"));
arrayList2.add(new Person(5,"name","place"));
arrayList2.add(new Person(6,"name","place"));

我想比较 arrayList1、arrayList2 并需要从 arrayList2 中找出不匹配的值。 我需要 id 值 5,6。

我该怎么做?

最佳答案

您可以使用内部循环来检查 arrayList2 中的 Person id 是否对应于 arrayList1 中的任何 Person id。如果找到某个人,您将需要一个标志来标记。

ArrayList<Integer> results = new ArrayList<>();

// Loop arrayList2 items
for (Person person2 : arrayList2) {
    // Loop arrayList1 items
    boolean found = false;
    for (Person person1 : arrayList1) {
        if (person2.id == person1.id) {
            found = true;
        }
    }
    if (!found) {
        results.add(person2.id);
    }
}

关于安卓 : Compare two ArrayList of objects and find unmatching ids from the second ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582099/

相关文章:

java - 在eclipse luna中运行maven项目

Android: DateUtils.formatDateTime 改变日期和时间顺序

java - 当我将函数 setVisible (View.gone) 应用于适配器时,如何从与适配器对应的列表中删除空格?

java - 每次我实例化新对象时,属性都会回到零

java | Json 字符串到对象(无需库)

javascript - 请解释有关javascript中原型(prototype)属性和函数构造函数的详细信息

java - 如何打印空字符串数组

android - ZXing-2.1 - 缺少库

java - 打印 ArrayList 的所有项目

java - 为什么ArrayList没有capacity()方法,却有ensureCapacity(int),而Vector、StringBuffer、StringBuilder两者都有?