Contains operator in java

Java: Check if Array Contains Value or Element

Whether in Java, or any other programming language, it is a common occurrence to check if an array contains a value. This is one of the things that most beginners tend to learn, and it is a useful thing to know in general.

In this article, we’ll take a look at how to check if an array contains a value or element in Java.

Arrays.asList().contains()

This is perhaps the most common way of solving this problem, just because it performs really well and is easy to implement.

First, we convert the array to an ArrayList . There are various ways to convert a Java array to an ArrayList, though, we’ll be using the most widely used approach.

Then, we can use the contains() method on the resulting ArrayList , which returns a boolean signifying if the list contains the element we’ve passed to it or not.

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(intList.contains(12)); System.out.println(nameList.contains("John")); 

Running this code results in:

Читайте также:  Алгоритм сортировки пузырьком python блок схема

Using a for-loop

A more basic and manual approach to solving the problem is by using a for loop. In worst case, it’ll iterate the entire array once, checking if the element is present.

Let’s start out with primitive integers first:

int[] intArray = new int[]1, 2, 3, 4, 5>; boolean found = false; int searchedValue = 2; for(int x : intArray)< if(x == searchedValue)< found = true; break; > > System.out.println(found); 

The found variable is initially set to false because the only way to return true would be to find the element and explicitly assign a new value to the boolean. Here, we simply compare each element of the array to the value we’re searching for, and return true if they match:

For Strings, and custom Objects you might have in your code, you’d be using a different comparison operator. Assuming you’ve validly ovverriden the equals() method, you can use it to check if an object is equal to another, returning true if they are:

String[] stringArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; boolean found = false; String searchedValue = "Michael"; for(String x : stringArray)< if(x.equals(searchedValue))< found = true; break; > > System.out.println(found); 

Running this code will result in:

Collections.binarySearch()

Additionally, we can find a specific value using a built-in method binarySearch() from the Collections class. The problem with binary search is that it requires our array be sorted. If our array is sorted though, binarySearch() outperforms both the Arrays.asList().contains() and the for-loop approaches.

If it’s not sorted, the added time required to sort the array might make this approach less favorable, depending on the size of the array and the sorting algorithm used to sort it.

binarySearch() has many overloaded variants depending on the types used and our own requirements, but the most general one is:

public static int binarySearch(Object[] a, Object[] key) 

Where a represents the array, and key the specified value we’re looking for.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Now, the return value might be a bit confusing, so it’s best to take Oracle’s official documentation in mind:

The return value of this method is the index of the searched key, if it is contained in the array; otherwise (-(insertion point) — 1), where insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"Bill", "Connor", "Joe", "John", "Mark">; // Array is already sorted lexicographically List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(Collections.binarySearch(intList, 2)); System.out.println(Collections.binarySearch(nameList, "Robin")); 

The first element is found, at position 1 . The second element isn’t found, and would be inserted at position 5 — at the end of the array. The return value is -(insertion point)-1 , so the return value ends up being -6 .

If the value is above equal to, or above 0 , the array contains the element, and it doesn’t contain it otherwise.

Java 8 Stream API

The Java 8 Stream API is very versatile and offers for concise solutions to various tasks related to processing collections of objects. Using Streams for this type of task is natural and intuitive for most.

Let’s take a look at how we can use the Stream API to check if an array contains an integer:

Integer[] arr = new Integer[]1, 2, 3, 4, 5>; System.out.println(Arrays.stream(arr).anyMatch(x -> x == 3)); 

And to do this with Strings or custom objects:

String[] arr = new String[]"John", "Mark", "Joe", "Bill", "Connor">; String searchString = "Michael"; boolean doesContain = Arrays.stream(arr) .anyMatch(x -> x.equals(searchString)); System.out.println(doesContain); 

Or, you can make this shorter by using a method reference:

boolean doesContain = Arrays.stream(arr) .anyMatch(searchString::equals); System.out.println(doesContain); 

Both of these would output:

Apache Commons — ArrayUtils

The Apache Commons library provides many new interfaces, implementations and classes that expand on the core Java Framework, and is present in many projects.

The ArrayUtils class introduces many methods for manipulating arrays, including the contains() method:

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; System.out.println(ArrayUtils.contains(intArray, 3)); System.out.println(ArrayUtils.contains(nameArray, "John")); 

Conclusion

In this article, we’ve gone over several ways to check whether an array in Java contains a certain element or value. We’ve gone over converting the array to a list and calling the contains() method, using a for-loop, the Java 8 Stream API, as well as Apache Commons.

Источник

Метод contains() в Java

Метод contains() – это метод Java, позволяющий проверить, содержит ли String другую подстроку или нет. Возвращает логическое значение, поэтому его можно использовать непосредственно внутри операторов if.

Синтаксис строкового метода “Container”

public boolean String.contains(CharSequence s)

s – это последовательность поиска

Этот метод возвращает true, только если эта строка содержит «s», иначе false.

NullPointerException – если значение s является нулем.

public class Sample_String < public static void main(String[] args) < String str_Sample = "This is a String contains Example"; //Check if String contains a sequence System.out.println("Contains sequence 'ing': " + str_Sample.contains("ing")); System.out.println("Contains sequence 'Example': " + str_Sample.contains("Example")); //String contains method is case sensitive System.out.println("Contains sequence 'example': " + str_Sample.contains("example")); System.out.println("Contains sequence 'is String': " + str_Sample.contains("is String")); >>

Contains sequence ‘ing’: true
Contains sequence ‘Example’: true
Contains sequence ‘example’: false
Contains sequence ‘is String’: false

Когда использовать метод Contains() ?

Это обычный случай в программировании, когда вы хотите проверить, содержит ли конкретная строка определенную подстроку. Например, если вы хотите проверить, содержит ли строка “The big red fox” подстроку “red.”Этот метод полезен в такой ситуации.

public class IfExample < public static void main(String args[]) < String str1 = "Java string contains If else Example"; // In If-else statements you can use the contains() method if (str1.contains("example")) < System.out.println("The Keyword :example: is found in given string"); >else < System.out.println("The Keyword :example: is not found in the string"); >> >

The Keyword :example: is not found in the string

Источник

contains() in Java

Java Course - Mastering the Fundamentals

contains() method is a part of the Java String class. It searches for a sequence or set of characters in a given string (note that it can not be used for a single character, we shall discuss it more later). It has a boolean return type, i.e., true is returned if the string contains the sequence of characters else false .

Syntax of contains() in Java

contains() method belongs to the Java String class.

Syntax of this method is as follows:

Here, ch represents the sequence of characters to be searched. Hence, the contains method is called on the given string.

Parameters of contains() in Java

contains() method takes a single parameter. It is the sequence of characters that is to be searched. It can be a sequence of characters like string, StringBuffer, etc. Other datatypes like int shall result in an incompatible type error.

For example:

Here, ABC is the sequence of characters taken as the parameter.

Return Values of contains() in Java

Return Type: boolean

Since contains() is a boolean method. It returns —

  • true: If sequence of characters is present in the string
  • false: If the sequence of characters is not present in the string.

Exceptions of contains() in Java

The contains() method throws NullPointerException in case the value of the sequence of characters is null .

In the above program, NullPointerException occurs since we have passed null as a parameter for the method.

Example

Let’s consider a short example to see the use case of contains( ) method.

In the above Program, string str is declared. The method contains() has been used to check if the character sequences are a substring of str or not. If yes, true is returned, and false otherwise.

Note that for an empty string, true is returned since it is a subset of every string.

What is contains() method in Java?

Let’s discuss how the contains() method works internally and its signature.

The signature of contains () method is as follows:

From the signature, it is visible that it has a boolean return type. Let’s dive in and look at its internal implementation. (This is just for the sake of understanding, don’t worry much about the implementation)

Inside the method, first of all, the conversion of a sequence of characters to a string occurs. Further, the indexOf method is called. This method returns 0 or any higher number if it finds the string; otherwise, it returns -1. So once it is executed, the contains method returns true when the indexOf method returns 0 or any higher number; otherwise, it returns false.

More about the contains() method in Java

We have seen the use cases of contains() method. However, there are some limitations that need to be considered.

  • This method can not be used for searching a single character.
  • This method can not be used to find the index of the searched string in the given string.

More Examples of String.contains() in Java

Example 1: Java String contains()

Now that we have covered the basics of contains() let’s look at an example. Suppose you have a list of email addresses of the format «name»»age»@xyz.com. You need to check which email belongs to James. Here, contains() method can be called on the email addresses, let us see how:

(For the example we have just considered two emails, we can have a list of the same and using a loop contains method can be called on every element of the list i.e., every email address). So here we have called the contains() method on two strings representing two email addresses. One with the desired Name or string of characters (which returns true ). For the other string, the method returns false since no matching character sequence is found. Hence, we know which email address belongs to the particular user.

Example 2: Using contains() With if. else

We can use the method inside an if — else block as well. Let us look at the implementation. Consider a case where you need to perform some modifications or operations on the strings containing a particular sequence of characters. In this case, contains method with if-else block can be used. Let us see how

In the above program, we have checked if the string contains the desired sequence of characters or not, «World» in this case. Since here it does. Thus we have performed the desired string operation. Here, the concat method is used to append strings.

Example 3: Using case insensitive check

contains() method is case sensitive, however with some modifications we can use this method for case insensitive check.

Basically we can take help of toLowerCase() or toUpperCase() method. This way, both the string and sequence of characters are converted to lower case or upper case and can easily be checked. Below is the implementation.

In the above example, we have converted both the sequence and string to lowercase and uppercase for checking.

Example 4: Contains() with single character

In the above program, We used contains method for a single character ‘S’. However, this results in an error. Hence, contains method can not be used for a single character.

Conclusion

  • contains () method is a built-in Java method that helps us check if a sequence of characters is present inside a given string or not.
  • The return type of this method is boolean , thus returning true or false.
  • It takes a single parameter,i.e., the sequence of characters to be searched.
  • Major Application of this method includes verification tasks like checking if a string is a substring of the other.

Источник

Оцените статью