Find if a String is present in an array

JavaArrays

Java Problem Overview


OK let's say I have an array filled with {"tube", "are", "fun"} and then I have a JTextField and if I type either one of those commands to do something and if NOT to get like a message saying "Command not found".

I tried looking in Java docs but all I am getting is things that I don't want like questions and stuff... so, how is this done? I know there is a "in array" function but I'm not too good with combining the two together.

Thanks.

Here is what I have so far:

String[] dan = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = dan.contains(say.getText());

but I am getting cannot find symbol in dan.contains

Java Solutions


Solution 1 - Java

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

Solution 2 - Java

String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");

Solution 3 - Java

Use Arrays.asList() to wrap the array in a List<String>, which does have a contains() method:

Arrays.asList(dan).contains(say.getText())

Solution 4 - Java

This can be done in java 8 using Stream.

import java.util.stream.Stream;
    
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());

Solution 5 - Java

If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch(). Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontestView Question on Stackoverflow
Solution 1 - JavaPablo FernandezView Answer on Stackoverflow
Solution 2 - Java卢声远 Shengyuan LuView Answer on Stackoverflow
Solution 3 - JavaJohn KugelmanView Answer on Stackoverflow
Solution 4 - JavaDream LaneView Answer on Stackoverflow
Solution 5 - JavaJim GarrisonView Answer on Stackoverflow