1

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
    }
   }
}
2
  • You can test this real quick in anonymous code within Developer console using System.Debug('Element:' + s); on do something.
    – Mahmood
    Oct 20 at 15:59
  • @Mahmood i know, just dont wanna write that cause doesnt matter. I am asking for another way to do it. Loop in loop seems to straightforward.
    – Terdivi
    Oct 20 at 16:02
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.