Android:比较两个ArrayList对象,并从第二个ArrayList中找到不匹配的ID

SKK*_*SKK 6 android compare arraylist object pojo

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

例如:

Person.java

private int id;
private String name;
private String place;
Run Code Online (Sandbox Code Playgroud)

MainActivity.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"));
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

Sim*_*mas 17

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)