Search code examples
javalistcontain

Java List contains element of another list of a different type


I would like to ask if there is a better way of find if a List contains at least one element of another List of a different type.

For instance

public class AnotherType{
  private int x;
  private String label;
  ....
}


List<String> list1 = new ArrayLis<String>();
list1.add("inst1");
list1.add("inst2");
list1.add("inst3");
List<AnotherType> list2 = new ArrayList<AnotherType>();
list2.add(new AnotherType(1,"inst7"));
list2.add(new AnotherType(1,"inst1"));

Now I want to find that the list2 in the index 1(second element) contains the element "inst1" that exists in list1. Is that a better than make one loop inside the other? I work with java 1.6


Solution

  • If you represent list1 as a HashSet, the .contains() operation would be much faster, O(1), as compared to ArrayList.contains(), which would be O(n).

    List<String> list1 = new ArrayLis<String>();
    list1.add("inst1");
    list1.add("inst2");
    list1.add("inst3");
    
    List<AnotherType> list2 = new ArrayList<AnotherType>();
    list2.add(new AnotherType(1,"inst7"));
    list2.add(new AnotherType(1,"inst1"));
    
    Set<String> set1 = new HashSet<>(list1);
    
    for(AnotherType elem : list2) {
         if(set1.contains(elem.getLabel())) {
             //  Do your thing here.
             return true;
         }
    }