Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

I have a String[] with values like so:

public static final String[] VALUES = new String[] {"QW","WE","ER","RT"};

Given String s, is there a good way of testing whether VALUES contains s?

1 Answer

0 votes
by (46k points)

There are several methods to do this:

Using Array.BinarySearch()

Using this method, we need to search a sorted array by repeatedly dividing the search interval in half until the value is found or the interval is empty.

public static int

   binarySearch(data_type arr, data_type key)

Using Linear search:

Using this method, array or list is traversed sequentially and every element is checked.

for (int element : arr)

{

   if (element == toCheckValue)

}

       return true;

List.contains() method:

If you want to check that a specified element exists in the given list or not.

public boolean contains(Object)

where object-element to be searched for.

Using stream.anyMatch method:

If you are using JAVA 8 or above you can try this method

boolean anyMatch(Predicate<T> predicate)

Where T is the type of input to the predicate

and the function returns true if any elements of

the stream match the provided predicate,

otherwise false.

For your problem test this:

String[] values = {"QW","WE","ER","RT"};

boolean contains = Arrays.stream(values).anyMatch("s"::equals);

  

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Apr 11, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...