Java element contained in array

How to check if an array contains a value in Java

In this short article, you’ll learn how to check if an array contains a certain value in Java. We will look at different examples of string as well as primitive arrays to find out if a certain value exists.

String[] names = "Atta", "John", "Emma", "Tom">; // convert array to list ListString> list = Arrays.asList(names); // check if `Emma` exists in list if(list.contains("Emma"))  System.out.println("Hi, Emma 👋"); > 

You should see the following output:

In Java 8 or higher, you can also use the Stream API to check if a value exists in an array as shown below:

String[] names = "Atta", "John", "Emma", "Tom">; // check if `Atta` exists in list boolean exist = Arrays.stream(names).anyMatch("Atta"::equals); if(exist)  System.out.println("Hi, Atta 🙌"); > 
String[] names = "Atta", "John", "Emma", "Tom">; // convert array to list ListString> list = Arrays.asList(names); // check 'Atta' & `John` if (list.containsAll(Arrays.asList("Atta", "John")))  System.out.println("Hi, Atta & John 🎉"); > 
int[] years = 2015, 2016, 2017, 2018, 2019, 2020>; // loop all elements for (int y : years)  if (y == 2019)  System.out.println("Goodbye, 2019!"); break; > > 

With Java 8 or higher, you can convert the primitive array to a Stream and then check if it contains a certain value as shown below:

// Integer Array int[] years = 2015, 2016, 2017, 2018, 2019, 2020>; // check if `2020` exits boolean yearExist = IntStream.of(years).anyMatch(x -> x == 2019); if(yearExist)  System.out.println("Welcome 2020 🌟"); > // Long Array long[] prices = 12, 15, 95, 458, 54, 235>; // check if `54` exits boolean priceExist = LongStream.of(prices).anyMatch(x -> x == 54); if(priceExist)  System.out.println("Yup, 54 is there 💰"); > 
Welcome 2020 🌟 Yup, 54 is there 💰 

You might also like.

Источник

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:

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.

Источник

How to Check if Java Array Contains a Value?

How to Check if Java Array Contains a Value?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

How to Check if Java Array Contains a Value?

  • Simple iteration using for loop
  • List contains() method
  • Stream anyMatch() method
  • Arrays binarySearch() for sorted array

Let’s look into all these methods one at a time.

1. Using For Loop

This is the easiest and convenient method to check if the array contains a certain value or not. We will go over the array elements using the for loop and use the equals() method to check if the array element is equal to the given value.

String[] vowels = < "A", "I", "E", "O", "U" >; // using simple iteration over the array elements for (String s : vowels) < if ("E".equals(s)) < System.out.println("E found in the vowels list."); >> 

2. Using List contains() method

We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value. Let’s use JShell to run the example code snippet.

jshell> String[] vowels = < "A", "I", "E", "O", "U" >; vowels ==> String[5] < "A", "I", "E", "O", "U" >jshell> List vowelsList = Arrays.asList(vowels); vowelsList ==> [A, I, E, O, U] jshell> vowelsList.contains("U") $3 ==> true jshell> vowelsList.contains("X") $4 ==> false 

Java Array Contains Value

3. Using Stream anyMatch() Method

If you are using Java 8 or higher, you can create a stream from the array. Then use the anyMatch() method with a lambda expression to check if it contains a given value.

jshell> List vowelsList = Arrays.asList(vowels); vowelsList ==> [A, I, E, O, U] jshell> Arrays.stream(vowels).anyMatch("O"::equals); $5 ==> true jshell> Arrays.stream(vowels).anyMatch("X"::equals); $6 ==> false 

4. Arrays binarySearch() for sorted array

If your array is sorted, you can use the Arrays binarySearch() method to check if the array contains the given value or not.

String[] vowels = < "A", "I", "E", "O", "U" >; System.out.println("Unsorted Array = " + Arrays.toString(vowels)); Arrays.parallelSort(vowels); System.out.println("Sorted Array = " + Arrays.toString(vowels)); int index = Arrays.binarySearch(vowels, "X"); if (index < 0) < System.out.println("X not found in the array"); >else
Unsorted Array = [A, I, E, O, U] Sorted Array = [A, E, I, O, U] X not found in the array 

Checking if Array Contains Multiple Values

What if we want to check if the array contains multiple values. Let’s say you want to check if a given array is the subset of the source array. We can create nested loops and check each element one by one. There is a cleaner way by converting arrays to list and then use the containsAll() method.

String[] vowels = < "A", "I", "E", "O", "U" >; String[] subset = < "E", "U" >; boolean foundAll = Arrays.asList(vowels).containsAll(Arrays.asList(subset)); System.out.println("vowels contains all the elements in subset = " + foundAll); 

Output: vowels contains all the elements in subset = true

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Candy css 13102 db3 07
Оцените статью