我想比较两个对象的 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/