How to search for a value in a list using Java?

In Java, you can use the contains() method to determine if a List contains a specific value.

Example code:

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

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("orange");

        // 判断List中是否包含某个值
        if (list.contains("banana")) {
            System.out.println("List中包含banana");
        } else {
            System.out.println("List中不包含banana");
        }
    }
}

Result of execution:

List中包含banana

In the example above, we created a List and added a few elements to it. We then used the contains() method to check if the List contains the value “banana” and printed the corresponding message based on the result.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds