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;
}
}
4 Answers 4
You can use Java Streams to get the first String that match:
Optional<String> result = Stream.of(vals).filter(list::contains).findFirst();
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".
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
.
-
That would change the semantics of the program, though. For example, the proposed program would recognize
"val1val2"
, while OP's program wouldn't.Turing85– Turing852021年03月04日 21:41:25 +00:00Commented Mar 4, 2021 at 21:41 -
@Turing85 True, depending on the domain of possible values. I assume from this kind of code that we have a limited number of known values. I’ll add a cautionary note to the answer, thanks.Basil Bourque– Basil Bourque2021年03月04日 21:45:32 +00:00Commented Mar 4, 2021 at 21:45
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"
.
if
-condition (missing)
).