Check if list contains value java

How to check if array contains a value in java

Check if array contains value in java
This article will detail out 5 different methods to check if array contains a value in java with example programs.
Following are the methods to check the presence of a value in java array

  1. Check whether a string array contains a given string value.
  2. If the string exists in the array, then get the index of its position in array.

Method 1 : Looping over the array
This is a conventional and most used method where the array of strings is iterated using a for loop and the value at every index is compared with the value to be searched in the array.
A boolean variable is set if any array value matches with the string. At the end of the loop, this boolean variable is checked to determine if the array contains the string.

public class ArrayContainsChecker < public static void main(String[] args) < methodOne(); >static void methodOne() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // initialize boolean variable boolean isExists = false; // iterate over array for (int i = 0; i < array.length; i++) < // get the value at current array index String arrayValue = array[i]; // compare values if (valueToSearch.equals(arrayValue)) < isExists = true; // if value is found, terminate the loop break; >> if (isExists) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Читайте также:  Vertical Line in html

Use == operator to check for equality when comparing primitive types such as int, long, float, double etc.
Note that in this example, we are using a simple for loop with an index.
But, we may also use an enhanced for loop to iterate over the array , if we do not require the index of the value to check.

Method 2 : Using List.contains()
Another method to check if an array contains an element is by using a list.
This method first converts the array to a java.util.List and then uses contains() method of java.util.List to check if the string exists in the list.

contains() method returns true if the value supplied as argument exists in the list and false otherwise. In other words, it checks if the list contains the supplied value.
Array is converted to a list using asList method of java.util.Arrays . This method takes an array as argument and returns a List with its elements populated with the contents of array.

import java.util.Arrays; import java.util.List; public class StringChecker < public static void main(String[] args) < methodTwo(); >static void methodTwo() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // convert the array to a list List list = Arrays.asList(array); // check if string exists in list if (list.contains(valueToSearch)) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Method 3 : Using Apache Commons Library
This method utilizes ArrayUtils class from Apache Commons Library.
This class has a method contains() which takes two arguments : an array and a value. It searches for the value in the array and returns true if the value is found in the array, false otherwise.

import org.apache.commons.lang.ArrayUtils; public class StringChecker < public static void main(String[] args) < methodThree(); >static void methodThree() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // check if string exists in array if (ArrayUtils.contains(array, valueToSearch)) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Apache Commons can be included using the following dependencies of Maven and Gradle. Use as per to the build tool suitable to you.

 org.apache.commons commons-lang3 3.9 
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

Method 4 : Using Arrays.binarySearch()
java.util.Arrays has a binarySearch() method which searches for a value in an array using binary search algorithm.
This method takes two arguments :
1. an array, and
2. the item to search in the array
and returns the index of the item in the array.
It returns -1 if the element is not found in the array. Note that this method requires the array to be sorted before performing the search operation.

import java.util.Arrays; public class StringChecker < public static void main(String[] args) < methodFour(); >static void methodFour() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "one"; // sort the array Arrays.sort(array); // search the value and get its index int index = Arrays.binarySearch(array, valueToSearch); // if index is not -1 then value is present if (index != -1) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Method 5 : Java 8 anyMatch()
With java 8 stream you can directly get an element matching some value. For using streams, the array should be converted to a collection class.
Convert it to a java.util.List using asList() method of java.util.Arrays class.
On this list object call stream() method which returns a java.util.stream.Stream object.

Invoke anyMatch() method on this stream object. This method takes a java.util.function.Predicate object as argument.

A Predicate object can be created on the fly using java Lambda expression by writing an expression which returns a boolean value.

In the below example, the expression is s -> s.equals(valueToSearch) . Here s represents the elements of array and compares them with the value we want to search in the array.
Thus the line list.stream().anyMatch(s -> s.equals(valueToSearch)) compares the elements of the list with the value to search and returns true if any element of the list matches the string in variable valueToSearch .

import java.util.Arrays; import java.util.List; public class StringChecker < public static void main(String[] args) < methodFive(); >static void methodFive() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "one"; // convert the array to a list List list = Arrays.asList(array); // check if array contains value boolean isFound = list.stream().anyMatch(s -> s.equals(valueToSearch)); if (isFound) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Let’s tweak in

  1. binarySearch() method will return -1 even if the value is present in the array if the array is not sorted.
  2. binarySearch() method can also be used directly in situations when the index of the value in the array is required.
  3. Arrays.asList will throw a java.lang.NullPointerException if the array supplied as argument is null .
  4. ArrayUtils from Apache Commons library also iterates over the array and compares each element with the value to search.
  5. There are different overloaded versions of contains method in ArrayUtils from Apache Commons library which act on arrays of various data types such as char , float , double , int , long , short etc.
  6. All the above methods work on string arrays but they can be used to search an element in array of other data types such as int array, char array etc.

Hope the article was useful.

Источник

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.

Источник

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