Contains in Java, how to search a text in an Arraylist?

Asked

Viewed 1,013 times

8

In C# there is the method contains of System.Linq that searches text in a list, I did the tests in Java and I did not find a similar way even knowing that in Java 8 has expression, there is some way to do this with expression in Java?

Example:

ArrayList<String> strListas = new ArrayList<>();
strListas.add("Paulo");
strListas.add("Adriano");
strListas.add("Paula");

strListas.Contains("Pa");

Upshot:

Paulo e Paula
  • I believe this is possible only with loop.

  • @diegofm has an example to give, please thank you!

3 answers

17


List<String> list = new ArrayList<>();
list.add("Paulo");
list.add("Adriano");
list.add("Paula");
    
List<String> resultado = list.stream()
                            .filter(s -> s.contains("Pa"))
                            .collect(Collectors.toList());
resultado.forEach(System.out::println);

Exit:

Paul

Paula

  • I liked this one, it plays the expected role, I just can’t vote for it, it looks like it has a score. I’ll wait. Thank you!

  • note that when using stream it is not possible to stop the execution in the middle of the list if you found the desired object and increase the performance, the stream will go through the entire list and only then will return the value, in these specific cases use the same

10

I guess you’ll have to go through the list and make a loop to look for.

for (String valor: strListas){
 valor.contains('Pa')
}
  • 1

    Thank you. It’s a way I wanted to avoid, but it’s quite natural. I can’t vote yet.

7

If you need a procuca with case insensitive, use Pattern:

ArrayList<String> strList = new ArrayList<>();

strList.add("Paula"); // será encontrado
strList.add("Paulo"); // será encontrado
strList.add("paula"); // será encontrado
strList.add("Pedro");
strList.add("Pedro pa"); // será encontrado

Pattern p = Pattern.compile("Pa", Pattern.CASE_INSENSITIVE);

for (String nome : strList) {
    Matcher m = p.matcher(nome);
    if (m.find()) {
        System.out.println("Nome encontrado: " + nome);
    }
}
  • Thank you, what I did test and I joined your solution with Felipe’s, it worked too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.