Java – How to search a string in a List?

In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList.

JavaExample1.java

package com.mkyong.test;

import java.util.ArrayList;
import java.util.List;

public class JavaExample1 {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Kotlin");
        list.add("Clojure");
        list.add("Groovy");
        list.add("Scala");

        List<String> result = new ArrayList<>();
        for (String s : list) {
            if (s.contains("Java")) {
                result.add(s);
            }

            /*
            if (s.startsWith("J")) {
                result.add(s);
            }
            */

            /* regex
            if (s.matches("(?i)j.*")) {
                result.add(s);
            }
            */
        }

        System.out.println(result);

    }

}

Output


[Java]

For Java 8, it’s much easier now.

JavaExample2.java

package com.mkyong.test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JavaExample2 {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Kotlin");
        list.add("Clojure");
        list.add("Groovy");
        list.add("Scala");

        List<String> result = list
                .stream()
                .filter(x -> x.contains("Java"))
                .collect(Collectors.toList());

        System.out.println(result);

    }

}

Output


[Java]

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar