Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if a String is present in an array [duplicate]

Tags:

java

arrays

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

like image 312
test Avatar asked Aug 26 '10 03:08

test


People also ask

How do you check if a string is repeated in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate.

How do you check if there is a duplicate in an array Java?

One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.

How do you check if an array contains the same value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


2 Answers

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

like image 120
Pablo Fernandez Avatar answered Oct 04 '22 10:10

Pablo Fernandez


String[] a= {"tube", "are", "fun"}; Arrays.asList(a).contains("any"); 
like image 36
卢声远 Shengyuan Lu Avatar answered Oct 04 '22 09:10

卢声远 Shengyuan Lu