Finding string in array java

How to Search an Element in Java Array with Example? ArrayUtils Tutorial

While programming in Java, many times we need to check if a String array contains a particular String or an integer array contains a number or not. Though array is an object in Java but it does not provide any convenient method to perform searching elements or finding elements. Sometimes you even need an index of an item stored in Array, unfortunately, Java API does not provide any direct method. Thanks to Open Source Apache Commons provides a utility class called ArrayUtils which allows you to check for an Item in Array, find its index in the array, find its lastIndex in Array and perform several other common operations.

In fact, ArrayUtils has overloaded methods for different kinds of Array like String, int, float, double, Object, etc, which makes this kind of programming task trivial. In this article, we will see an Apache commons example of How to use ArrayUtils class to search an item in Array and find its index.

Btw, if you find it on your own, you can also use binary search and linear search algorithm to scan array and check if a given element exists on array or not. You can also find their index or position in the array.

Java program to check and find an index of element in a String array

Here is complete code example of Apache Commons ArrayUtils class which makes checking for an item in array extremely easy, no matter which kind of array it is. ArrayUtils has overloaded method for all kinds of array. We will ArrayUtils.contains() and ArrayUtils.indexOf() method to check if Array contains an item and what is an index of that item.

Читайте также:  Свой бот телеграмм php

If you want to do it without Apache commons ArrayUtils class, you can just convert your array to ArrayList by following any of these three methods of converting Array to ArrayList and you can leverage contains() , indexOf() and lastIndexOf() method of List class to perform these operations.

By the way you need to include Apache commons JAR in your classpath to execute this example, if you are using Maven you can just include Apache common dependency in your pom.xml file

import java.util.Arrays ;
import java.util.List ;
import org.apache.commons.lang.ArrayUtils ;

/**
*
* Java program to check if an Array contains an Item or not
* and finding index of that item. For example, How to check if
* a String array contains a particular String or not and What is
* index of that String in Java program.
*
* @author http://java67.blogspot.com
*/
public class ArrayTest

public static void main ( String args [])

String [] programming = new String [] < "Java" , "C++" , "Perl" , "Lisp" >;

// Checking an String in String Array by converting Array To ArrayList
List < String > programmingList = Arrays. asList ( programming ) ;

//Checking does this Array contains Java
boolean result = programmingList. contains ( «Java» ) ;

System. out . println ( «Does programming Array contains Java? » + result ) ;

int index = programmingList. indexOf ( «Java» ) ;

System. out . println ( «Index of Java in programming Array is : » + index ) ;

// Checking item in Array using Apache Commons ArrayUtils class

System. out . println ( «Does programming array has Java? » +

ArrayUtils. contains ( programming, «Java» )) ;
System. err . println ( «What is index of Java in array? » +

ArrayUtils. indexOf ( programming, «Java» )) ;

Output
Does programming Array contain Java ? true
Index of Java in programming Array is : 0
Does programming array has Java ? true
What is the index of Java in the array ? 0

Java program to find index of object in Array in Java with example

These were two easy way to check items in Array and finding the index of an Item on Array in Java. Both of these techniques will work in any kind of Array like String array or Object array. ArrayUtils even accept primitive arrays e.g. int, float, long etc.

  • Top 15 Data Structure and Algorithm Interview Questions (see here)
  • How to reverse an array in place in Java? (solution)
  • How to remove duplicate elements from an array in Java? (solution)
  • How to check if a number is binary in Java? (answer)
  • Top 30 Array Coding Interview Questions with Answers (see here)
  • How to find all pairs whose sum is equal to a given number in Java (solution)
  • Top 30 linked list coding interview questions (see here)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • Write a Program to remove duplicates from an array without using Collection API? (program)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • How to compare two arrays in Java? (answer)
  • Top 20 String coding interview questions (see here)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • How to find a missing number in an array? (answer)

P. S. — If you are looking for some Free Data Structure and Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It’s completely free and all you need to do is create a free Udemy account to enroll in this course.

Источник

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

We will be performing the following tasks :

  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

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.

Источник

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