Check if one list contains element from the other

前端 未结 12 2601
没有蜡笔的小新
没有蜡笔的小新 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:33

    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.

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

    If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

    !Collections.disjoint(list1, list2);
    

    If you need to test a specific property, that's harder. I would recommend, by default,

    list1.stream()
       .map(Object1::getProperty)
       .anyMatch(
         list2.stream()
           .map(Object2::getProperty)
           .collect(toSet())
           ::contains)
    

    ...which collects the distinct values in list2 and tests each value in list1 for presence.

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

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

    if (list1.contains(Object o))
    {
       //do this
    }
    
    0 讨论(0)
  • 2020-11-30 21:43

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

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

    boolean var = lis1.stream().anyMatch(element -> list2.contains(element));
    
    0 讨论(0)
  • 2020-11-30 21:48

    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);
    
    0 讨论(0)
提交回复
热议问题