11

In python, you can use a very simple if statement to see if what the user has entered (or just a variable) is in a list:

myList = ["x", "y", "z"]
myVar = "x"

if myVar in x:
    print("your variable is in the list.")

How would I be able to do this in Java?

user3312175
  • 187
  • 2
  • 2
  • 7

5 Answers5

13

If your array type is a reference type, you can convert it to a List with Arrays.asList(T...) and check if it contains the element

if (Arrays.asList(array).contains("whatever"))
    // do your thing
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
3
String[] array = {"x", "y", "z"};

if (Arrays.asList(array).contains("x")) {
    System.out.println("Contains!");
}
DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35
2

Here is one solution,

String[] myArray = { "x", "y", "z" };
String myVar = "x";
if (Arrays.asList(myArray).contains(myVar)) {
    System.out.println("your variable is in the list.");
}

Output is,

your variable is in the list.
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You could iterate through the array and search, but I recommend using the Set Collection.

Set<String> mySet = new HashSet<String>();
mySet.add("x");
mySet.add("y");
mySet.add("z");
String myVar = "x";

if (mySet.contains(myVar)) {
  System.out.println("your variable is in the list");
}

Set.contains() is evaluated in O(1) where traversing an array to search can take O(N) in the worst case.

Brian
  • 7,098
  • 15
  • 56
  • 73
1

Rather than calling the Arrays class, you could just iterate through the array yourself

String[] array = {"x", "y", "z"};
String myVar = "x";
for(String letter : array)
{
    if(letter.equals(myVar)
    {
         System.out.println(myVar +" is in the list");
    }
}

Remember that a String is nothing more than a character array in Java. That is

String word = "dog";

is actually stored as

char[] word = {"d", "o", "g"};

So if you would call if(letter == myVar), it would never return true, because it is just looking at the reference id inside the JVM. That is why in the code above I used

if(letter.equals(myVar)) { }