0

I was curious how to check whether a value is in an array in Java

import java.util.Scanner;
Scanner keyboard = new Scanner(System.in);

String[] choices = {"choiceA", "choiceB", "choiceC"};

String userChoice = keyboard.nextLine();

Let's say we wanted to check if whatever value the user inputs into userChoice is in the choices array, how could I do that?

losowy
  • 25
  • 4
  • 1
    iterate over the elements and use equals, or turn it into a List, and use the contains method – Stultuske May 12 '21 at 16:00
  • 3
    Does this answer your question? [How do I determine whether an array contains a particular value in Java?](https://stackoverflow.com/questions/1128723/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java) – code11 May 12 '21 at 16:03
  • Create List or Set and use contains() method. – Mayur May 12 '21 at 17:44

2 Answers2

4

Here's what you do

boolean choicesContainUserChoice = Arrays.asList(choices).contains(userChoice);

or if you care about performance a lot

boolean choicesContainUserChoice = false;
for (int i = 0; i < choices.length; i++ ) {
    if (Objects.equals(choices[i], userChoice) {
         choicesContainUserChoice = true;
         break;
    }
}
Ilya Sazonov
  • 1,006
  • 10
  • 16
0

There are several ways to do it.

  1. Linear search
      boolean test = false;
        for (int element : arr) {
            if (element == toCheckValue) {
                test = true;
                break;
            }
        }
  1. Binary search
        int res = Arrays.binarySearch(arr, toCheckValue);
        boolean test = res > 0 ? true : false;
  1. Using List.contains() method
         boolean test
            = Arrays.asList(arr)
                  .contains(toCheckValue);
  1. Using stream.anyMatch() method
         boolean test
            = IntStream.of(arr)
                  .anyMatch(x -> x == toCheckValue);
  1. Using Arrays.stream() method
         boolean test
            = IntStream.of(arr)
                  .anyMatch(x -> x == toCheckValue);

Reference: https://www.geeksforgeeks.org/check-if-a-value-is-present-in-an-array-in-java/