如何在有/不迭代每个列表的情况下比较两个列表



如何在不迭代每个列表的情况下比较上述两个列表?我想比较人员 1 列表而不迭代人员列表。当匹配发生时,它打印匹配的对象,否则它必须打印不匹配的对象。我必须在不迭代第二个列表的情况下执行此操作。

import java.util.*;
public class Person implements Comparable<Person> {
String name;
int age;
String mail;
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Person(String name, int age, String mail) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return name + " : " + age;
}
public int compareTo(Person p) {
return getMail().compareTo(p.getMail());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return false;
}
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
people.add(new Person("Homer", 38, "shankar@gmail.com"));
people.add(new Person("Marge", 35, "shankar6@gmail.com"));
people.add(new Person("Bart", 15, "ramr@gmail.com"));
people.add(new Person("Lisa", 13, "ramkumar@gmail.com"));
System.out.println("t" + people);
List<Person> people1 = new ArrayList<Person>();
people1.add(new Person("jug", 38, "jug@gmail.com"));
people1.add(new Person("benny", 35, "benny@gmail.com"));
people1.add(new Person("Bart", 15, "ramr@gmail.com"));
people1.add(new Person("Lisa", 13, "ramkumar@gmail.com"));
for (Person people : people) {
if (people1.contains( people)) { 
System.out.println("matched");
System.out.println(people);
} else {
System.out.println("not matched");
System.out.println(people);
}
}
}
}

预期输出:

matched
Bart : 15 :ramr@gmail.com

首先,你需要有一个正确的equals方法实现。然后,您可以使用"仅保留此列表中包含在指定集合中的元素(可选操作("的List#retainAll。换句话说,从此列表中删除未包含在指定集合中的所有元素"。

如果要保留原始列表,请将原始列表复制到某个列表,例如:copyofPeople然后您可以使用copyofPeople.retainAll(people1)。现在,如果copyofPeople是空白的(copyofPeople.size()==0(,则没有共同的元素。

如果您的逻辑相等取决于此人的电子邮件,则等于方法应如下所示:

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (mail == null) {
if (other.mail != null)
return false;
} else if (!mail.equals(other.mail))
return false;
return true;
}

集合具有:

people.retainAll(people1) // for intersection
people.addAll(people1) // for union

如果你使用的是Java 8,那么你也可以使用Stream。

for (Person p : people) {
if(people1.stream().filter(i -> i.equals(p)).findFirst().isPresent()){
System.out.println("matched");
System.out.println(p);
}
else{
System.out.println("not matched");
System.out.println(p);
}
}

在这里,我覆盖了 Person 类中的等于方法,如果一个对象的所有属性都与另一个对象匹配,则返回 true。

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person p = (Person) obj;
if(getName() == p.getName() && getAge() == p.getAge() && getMail() == p.getMail())
return true;
else
return false;
}    

最新更新