Jeeppp
Jeeppp

Reputation: 1573

Check if a String contains an element from a List

I'm have defined a list like the below

List<String> list = List.of("val1", "val2", "val3");

Now I have the below String

String myStr = "rel1,wel12,val1";

Now I need to check if the String has anyone one of the elements of the list(in the above case its true as it has val1, next is get that value into a variable

I have tried the below and it works, but I'm sure there is a better way to do that using any of the Collections libraries

List<String> list = List.of("val1", "val2", "val3");
String myStr = "rel1,wel12,val1";

String matchedStr =StringUtils.EMPTY;
String[] vals = myStr.split(",");
for(String val:vals) {
    if(list.contains(val){
      matchedStr=val;
      break;
    }
}

Upvotes: 1

Views: 1251

Answers (4)

PPartisan
PPartisan

Reputation: 8231

I would favour Zobayer's answer, or using List#retainAll.

final List<String> first = List.of("one", "two", "three");
final List<String> out = new ArrayList<>(Arrays.asList("five,four,three".split(",")));

out.retainAll(first);

out contains the single entry, "three".

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338574

Depending on the possible values in the problem domain, there may be no need to split the input string. Just call String#contains.

If so, you can flip your logic. Rather than loop on the split parts, loop on the target list of strings. For each string in the list, ask if your unprocessed input string contains that element. If yes, bail out of the loop.

Tip: If this code is in a method returning a string, and returns null if no match was found, learn about returning an Optional.

Upvotes: 0

Zobayer Hasan
Zobayer Hasan

Reputation: 2327

Your way is alright if the lists aren't too big. I am considering the string as a list too because it can be made one from splitting it as you've done already. You can make a set from the bigger one, and iterate on the smaller one.

Another way to go would be to find the intersection of two lists.

List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");

Now we can find the inttersection:

Set<String> result = list.stream()
  .distinct()
  .filter(otherList::contains)
  .collect(Collectors.toSet());

The result should contain "red" and "green".

Some more info on collectors.

Upvotes: 0

flaxel
flaxel

Reputation: 4587

You can use Java Streams to get the first String that match:

Optional<String> result = Stream.of(vals).filter(list::contains).findFirst();

Upvotes: 1

Related Questions