[java] Check if one list contains element from the other

I have two lists with different objects in them.

List<Object1> list1;
List<Object2> list2;

I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame).

right now, I do it like this:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

But I think there is a better and faster way to do this :) Can someone propose it?

Thanks!

This question is related to java list find element

The answer is


With java 8, we can do like below to check if one list contains any element of other list

boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();

faster way will require additional space .

For example:

  1. put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )

  2. Go through the other list and check if any item is in the HashSet.

In this way each object is visited at most once. and HashSet is fast enough to check or insert any object in O(1).


According to the JavaDoc for the .contains(Object obj):

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

So if you override your .equals() method for your given object, you should be able to do: if(list1.contains(object2))...

If the elements will be unique (ie. have different attributes) you could override the .equals() and .hashcode() and store everything in HashSets. This will allow you to check if one contains another element in constant time.


To shorten Narendra's logic, you can use this:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element));

org.springframework.util.CollectionUtils

boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)

Return true if any element in 'candidates' is contained in 'source'; otherwise returns false

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);

You can use Apache Commons CollectionUtils:

if(CollectionUtils.containsAny(list1,list2)) {  
    // do whatever you want
} else { 
    // do other thing 
}  

This assumes that you have properly overloaded the equals functionality for your custom objects.


If you want to check if an element exists in a list, use the contains method.

if (list1.contains(Object o))
{
   //do this
}

Can you define the type of data you hold ? is it big data ? is it sorted ? I think that you need to consider different efficiency approaches depending on the data.

For example, if your data is big and unsorted you could try and iterate the two lists together by index and store each list attribute in another list helper. then you could cross check by the current attributes in the helper lists.

good luck

edited : and I wouldn't recommend overloading equals. its dangerous and probably against your object oop meaning.


to make it faster, you can add a break; that way the loop will stop if found is set to true:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something  
           break;
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

If you would have maps in stead of lists with as keys the attributeSame, you could check faster for a value in one map if there is a corresponding value in the second map or not.


Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to find

Find a file by name in Visual Studio Code Explaining the 'find -mtime' command find files by extension, *.html under a folder in nodejs MongoDB Show all contents from all collections How can I find a file/directory that could be anywhere on linux command line? Get all files modified in last 30 days in a directory FileNotFoundError: [Errno 2] No such file or directory Linux find and grep command together find . -type f -exec chmod 644 {} ; Find all stored procedures that reference a specific column in some table

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?