34

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!

1
  • Please let us know the type of stringArray. Commented Aug 4, 2017 at 6:01

11 Answers 11

27

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[].

Sign up to request clarification or add additional context in comments.

7 Comments

unsorted list is slow for contains, if you can do a HashSet you are doing a lot better
@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.
I will use the ArrayList, it only contains 5 string from a form. Thank you!
@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.
In case you have a String[] you can use Arrays.asList(array).contains(element);.
|
24

In SQL

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

In Java:

Arrays.asList("Alice", "Bob", "Carol").contains(x)

Comments

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

Comments

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.

2 Comments

You don't need to do this manually, Arrays.binarySearch() helps
@Colin, Binary search only works when the array is sorted.
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().

Comments

2
tabs[j].indexOf("lelamondeestgrand...")!=0

1 Comment

I think you missed a point here : stringArray is an array of String, not just a String, so the method indexOf does not exist.
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);

1 Comment

just found this question: Java in operator
1
if(myArrayList.contains("hello"))
{
    // yay
}

Comments

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.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.