Get element from list which contains element from another list

containsliststring

I have two Lists with diffeerent lenghts and want to check this value. It must be something list that:

List<String> first = new List<String>{'Test','Something'};
List<String> second = new List<String> {'es'}'

And comparing them must return me first element. So my only idea is to do that, but it seems too straightforward.

for(String s:first) {
   for(String s2:second){
    if(s.contains(s2)) {
    //do something
    }
   }
}

Best Answer

Unfortunately, since the second string is looking for a partial text match, I don't see a way to avoid looping over each element to compare them. If you had a full text element match, the inner loop could be removed in favor of a Set contains() method.

You should be careful of this "loop within a loop" approach. Unless you have tight control of the size of the lists, your code would grow exponentially as the length of the list grows.

IE:

first.size() == 2
second.size() == 2
//total loops == 4

//increase the lists by only one each, and the total is much larger
first.size() == 3
second.size() == 3
//total loops == 9
Related Topic