If you use the method RetainAll in the List the you will get the common objects between 2 Lists..\
Example:
consider the lists of integers, (just for the sake of the example) it will work with your class...
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5));
List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 3, 5));
List<Integer> list3 = new ArrayList<Integer>(list1);
list3.retainAll(list2);
System.out.println("List1:" + list1);
System.out.println("List2:" + list2);
System.out.println("List common:" + list3);
}
In your case the class contacts needs to be modified so the Method ArrayLst.retainAll() can somehow identify whether a Contact is the same as the other using as criteria the Phone number...
Modify/Improve the Contact Class by adding the HashCode and Equals:
but you need to use as criteria only the phone Number
public class Contact {
private String name;
private int phone;
public Contact(String name, int phone) {
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Contact [name=" + name + ", phone=" + phone + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + phone;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contact other = (Contact) obj;
if (phone != other.phone)
return false;
return true;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
}
Implement the List of Contacts and call the method RetainAll
public static void main(String[] args) {
List<Contact> list1 = new ArrayList<Contact>(Arrays.asList(new Contact(UUID.randomUUID().toString(), 1),
new Contact(UUID.randomUUID().toString(), 2), new Contact(UUID.randomUUID().toString(), 3),
new Contact(UUID.randomUUID().toString(), 4), new Contact(UUID.randomUUID().toString(), 5)));
List<Contact> list2 = new ArrayList<Contact>(Arrays.asList(new Contact(UUID.randomUUID().toString(), 1),
new Contact(UUID.randomUUID().toString(), 3), new Contact(UUID.randomUUID().toString(), 5)));
List<Contact> list3 = new ArrayList<Contact>(list1);
list3.retainAll(list2);
System.out.println("List1:" + list1);
System.out.println("List2:" + list2);
System.out.println("List common:" + list3);
}