Home > Java > javaTutorial > How to use contains in java

How to use contains in java

下次还敢
Release: 2024-05-08 03:54:16
Original
942 people have browsed it

The contains() method in Java checks whether a specific element or substring exists in a collection or string, and returns true to indicate inclusion, otherwise it returns false. It works with a variety of comparison and search operations on types such as List, Set, Map, and String.

How to use contains in java

contains() usage in Java

In Java, contains() method Used to check whether a set or string contains a specific element or substring. It is widely used for various comparison and search operations.

Syntax

<code class="java">boolean contains(Object element)</code>
Copy after login

Parameters

  • element - The element or child to search for String

Return value

  • Returns true if the collection or string contains the element or substring ; Otherwise, return false.

Usage example

List

<code class="java">List<String> names = new ArrayList<>();
names.add("John");
names.add("Mary");
names.add("Bob");

if (names.contains("John")) {
    // John 已存在于列表中
}</code>
Copy after login

Set

<code class="java">Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

if (numbers.contains(2)) {
    // 集合中包含数字 2
}</code>
Copy after login

Map

<code class="java">Map<String, Integer> ages = new HashMap<>();
ages.put("John", 30);
ages.put("Mary", 25);
ages.put("Bob", 35);

if (ages.containsKey("John")) {
    // John 已存在于映射中
}</code>
Copy after login

String

<code class="java">String str = "Hello World";

if (str.contains("World")) {
    // 字符串中包含子字符串 "World"
}</code>
Copy after login

Notes

  • contains The () method iterates over the entire collection or string, so it may be less efficient, especially if the collection or string is large.
  • For primitive types (such as int, char, etc.), you can use the equals() method for comparison instead of contains(). The
  • contains() method behaves differently with null values ​​depending on the collection type. For example, List and Set will treat null as a valid element, but Map will not.

The above is the detailed content of How to use contains in java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template