Check if one list contains element from the other

前端 未结 12 2600
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 20:45

I have two lists with different objects in them.

List list1;
List list2;

I want to check if element from list

相关标签:
12条回答
  • 2020-11-30 21:23

    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).

    0 讨论(0)
  • 2020-11-30 21:23

    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();
    
    0 讨论(0)
  • 2020-11-30 21:24

    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.

    0 讨论(0)
  • 2020-11-30 21:27

    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.

    0 讨论(0)
  • 2020-11-30 21:29

    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
    
    0 讨论(0)
  • 2020-11-30 21:32

    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.

    0 讨论(0)
提交回复
热议问题