java

How to find an element in a list in Java

In this tutorial, we are going to see different ways to search for an element in a list in Java. In the following Java programs, we will use a “for” loop with the following methods .contains(), .startsWith() or .matches() to search for an element or a string in an ArrayList.
 

Methode 1: How to find an element in a list Using the .contains() method

The contains() method is a Java method for checking whether a string contains another substring or not. It returns TRUE or FALSE.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        List<String> lang = new ArrayList<>();
        lang.add("Java");
        lang.add("PHP");
        lang.add("Python");
        lang.add("C++");

        List<String> res = new ArrayList<>();
        for (String i : lang) {
            if (i.contains("Python")) {
                res.add(i);
            }
        }
        System.out.println(res);
    }
}

Output:

[Python]

 

 

Method 2: How to find an element in a list Using the .startsWith() method

The startsWith() method of the String class is used to check the prefix of a string. It returns a Boolean value TRUE or FALSE depending on whether the given string begins with the specified letter or word.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        List<String> lang = new ArrayList<>();
        lang.add("Java");
        lang.add("PHP");
        lang.add("Python");
        lang.add("C++");

        List<String> res = new ArrayList<>();
        for (String i : lang) {
            if (i.startsWith("C")) {
                res.add(i);
            }
        }
        System.out.println(res);
    }
}

Output:

[C++]

 

 

Method 3: How to find an element in a list Using the .matches() method

The matches() method indicates whether or not a given string matches the given regular expression.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        List<String> lang = new ArrayList<>();
        lang.add("Java");
        lang.add("PHP");
        lang.add("Python");
        lang.add("C++");

        List<String> res = new ArrayList<>();
        for (String i : lang) {
            if (i.matches("(?i)c.*")) {
                res.add(i);
            }
        }
        System.out.println(res);
    }
}

Output:

[C++]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *