1

What I am trying to do is to find loop through a string then match them with an arrayList.

Say, I got this code working:

import java.io.*;
import java.text.ParseException;
import java.util.*;

public class Test_Mark4 {
    public static ArrayList<String> patterntoSearch;
    public static void main(String[] args) throws IOException, ParseException {
        String text = "Lebron James";
        patterntoSearch = new ArrayList();
        patterntoSearch.add("Lebron James");
        patterntoSearch.add("Michael Jordan");
        patterntoSearch.add("Kobe Bryant");
        System.out.println(patterntoSearch);
        System.out.println(text);
        boolean valueContained = patterntoSearch.contains(text);
        System.out.println(valueContained);
    }
}

However, what if I replace String text = "Lebron James"; with String text = "Lebron James 2017-218 NBA Hoops Card";? Clearly there is the string Lebron James in that string, but it got mixed with other words as well (which I would not care, and only care about the string Lebron James. I have thought about a for loop but unsure how to construct it.

0

1 Answer 1

2

You can use regular expression for that:

patterntoSearch.stream()
    .anyMatch(s -> text.matches(".*" + s + ".*"));

This returns boolean indicating whether any element in patterntoSearch is contained in text.

patterntoSearch.stream()
    .filter(s -> text.matches(".*" + s + ".*"))
    .collect(Collectors.toList());

This will return a list of words in patterntoSearch, that are contained in text. If you want only one, then:

patterntoSearch.stream()
    .filter(s -> text.matches(".*" + s + ".*"))
    .findAny()
    .orElse(null);

I have passed null as default, but you can provide any String.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.