32

I want to know if there's a way of doing something like this in Java :

if(word in stringArray) {
  ...
}

I know I can make a function for this but I just want to know if Java has already something for this.

Thank you!

codea
  • 1,232
  • 4
  • 18
  • 27

11 Answers11

26

There are many collections that will let you do something similar to that. For example:

With Strings:

String s = "I can has cheezeburger?";
boolean hasCheese = s.contains("cheeze");

or with Collections:

List<String> listOfStrings = new ArrayList<String>();
boolean hasString = listOfStrings.contains(something);

However, there is no similar construct for a simple String[].

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • unsorted list is slow for contains, if you can do a HashSet you are doing a lot better – bwawok Aug 25 '10 at 12:55
  • @bwawok, well, it is slow if `O(n)` is slow to you. But, it will be just as fast as any `contains` method for an array. – jjnguy Aug 25 '10 at 12:58
  • I will use the ArrayList, it only contains 5 string from a form. Thank you! – codea Aug 25 '10 at 12:58
  • @Justin 'jjnguy' Nelson o(n) is pretty darn slow for a simple in search... – bwawok Aug 25 '10 at 15:06
  • 1
    @bwawok, Well, if the elements are not in any order, and all you have is a list of them to begin with, it is the best case. I will agree that if you could use any other data structure `O(n)` stinks. – jjnguy Aug 25 '10 at 15:24
  • 1
    In case you have a `String[]` you can use `Arrays.asList(array).contains(element);`. – whiskeysierra Aug 26 '10 at 11:10
  • @Willi, indeed. You can convert the array to a list, and then use the contains method. – jjnguy Aug 26 '10 at 12:55
22

In SQL

x in ('Alice', 'Bob', 'Carol')

In Java:

Arrays.asList("Alice", "Bob", "Carol").contains(x)
demongolem
  • 9,474
  • 36
  • 90
  • 105
asmund.skalevik
  • 221
  • 2
  • 2
13

The Java language is designed to be powerful but also simple. There is no such operator in Java at the language level, but certainly libraries have been written to facilitate such queries.

If you want to know if some object is a member of some set of objects, then instead of an array, you should use -- what else? -- a Set. These data structures naturally allows such queries, and better yet, they're optimized for such queries.

You can easily check if a given string is in a Set<String> like this:

    String[] arr = { "Alice", "Bob", "Carol" };
    Set<String> names = new HashSet<String>(Arrays.asList(arr));

    System.out.println(names.contains("Alice")); // true
    System.out.println(names.contains("Dean")); // false

Using a HashSet, contains is a constant-time operation. This is much better than a linear search through an array.

You should familiarize yourself with what data structures are made available for you by the Java Collections Framework. They allow you to write codes that are idiomatic, maintainable, flexible, and supported by many of the powerful algorithms available for these data structures.

See also

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
7

Java has no "in" operator.

For arrays you need to iterate them and look for a matching item.

For Lists you can use the contains method.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
3

You can use java.util.Collection.contains() for collections. If what you have is a non-null array, you can use java.util.Arrays.asList(array).contains().

gpeche
  • 21,974
  • 5
  • 38
  • 51
2
tabs[j].indexOf("lelamondeestgrand...")!=0
Jon B
  • 51,025
  • 31
  • 133
  • 161
yobro
  • 29
  • 1
  • I think you missed a point here : stringArray is an array of String, not just a String, so the method indexOf does not exist. – codea Nov 22 '12 at 17:36
2

Without arrays:

public static <T> boolean in(T value, T... list) {
    for (T item : list) {
        if (value.equals(item))
            return true;
    }
    return false;
}

usage:

int val = 1;
assert in(val, 1,2,3,4);
Alexander Malakhov
  • 3,383
  • 2
  • 33
  • 58
1
if(myArrayList.contains("hello"))
{
    // yay
}
Brian
  • 6,391
  • 3
  • 33
  • 49
1

It first depends what the array is an array of. If it is an array of the exact words you can convert it to a regular collection and use the contains() method. If it is an array of sentences or phrases etc. you must iterate over it to tell.

The most general solution that will catch all these is to iterate as follows.

for(String s : stringArray)
{
  if(s.indexOf(word) > 0) return true;
}
return false;

This looks at every string in the array, and checks to see if the word is contained anywhere within it. It will return true after the first occurrance is found.

Fish
  • 459
  • 2
  • 6
0

If the array is sorted, you can use Arrays.binarySearch to find the data.

Like this:

   if (Arrays.binarySearch(stringArray, word)>=0)  {
     // word found in the array.
   }

If the array is unsorted, commons lang, has the ArrayUtils.indexOf method.

Finally, if you are searching a large array, then a parallel search may be worthwhile using ParallelArray, from JSR166 - coming in Java SE 7 and available now as a download. This article gives an introduction.

mdma
  • 56,943
  • 12
  • 94
  • 128
0

give us more details on what your problem looks like, and what you need to check. There are several different ways to do stuff like this. If you need to keep asking if item A is in set B.. make set B a HashSet, and you can call contains very quick. You can get the same effect in several java-ish ways, but they will vary depending on your data etc.

bwawok
  • 14,898
  • 7
  • 32
  • 43