Ronak Patel Ronak Patel - 8 months ago 18
Android Question

common objects in 2 ArrayList

I have 2

. And I want elements with common

ArrayList<Contact> phone_contacts;
ArrayList<Contact> registered_users;

I used below method to get common elements:

ArrayList<Contact> common_contacts = new ArrayList<Contact>(phone_contacts);

But, the result I get is empty. How can I get common phone contact in


public class Contact {
private String name;
private String phone;

public Contact(String name, String phone) { = name; = phone;

public String getName() {
return name;

public void setName(String name) { = name;

public String getPhone() {
return phone;

public void setPhone(String phone) { = phone;


First, if you are treating a phone number as an identifier, I would advise caution. Falsehoods Programmers Believe About Phone Numbers

With that said...

retainAll ultimately uses the equals method. Given that you have a custom object (and not something like a String or int that have a defined equals), the simplest method would be to define an equals method for Contact that returns true if the two have the same phone number.

However, that might not be what you are looking for. For example, equals might need to check the name in other contexts.

There are a couple other approaches you could take. Since you mentioned Android, Java 8 streams are currently out. An Iterator loop might do the job. Collect all of the phone numbers for registered users into a Set (so you have the unique list), then start with a List of all of your contacts, and remove any that don't have a phone number from that set.

Set<String> registeredPhoneNumbers = new HashSet<>();
for (Contact c : registered_users) {
List<Contact> common_contacts = new ArrayList<>(phone_contacts);
for (Iterator<Contact> iter = common_contacts.iterator(); iter.hasNext();) {
  Contact c =;
  if (!registeredPhoneNumbers.contains(c.getPhone())) {

Since you mentioned in comments that there could be a million distinct registered_users, this might be more space-efficient:

Set<String> phoneNumbers = new HashSet<>();
for (Contact c : phone_contacts) {

Set<String> overlappingNumbers = new HashSet<>();
for (Contact registered : registered_users) {
    if (phoneNumbers.contains(registered.getPhone())) {
List<Contact> common_contacts = new ArrayList<>();
for (Contact contact : phone_contacts) {
    if (overlappingNumbers.contains(contact.getPhone())) {

You may want to check the phone number for null as well.