A
A
Andrey Makarkin2018-04-24 09:49:42
Java
Andrey Makarkin, 2018-04-24 09:49:42

Checking if a key exists in an array. How?

Tell me please. There is an array:

String[] catsNames = {
      "Васька", 
      "Матроскин"
      };

How to check the presence of the "Matroskin" key in this array? given that not only can it not exist, but also the fact that it may not necessarily be "Matroskin". Instead, it may be "Barbos".

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-04-24
@shotlandec2

public class Example {
    private static final String[] catsNames = { "Васька", "Матроскин" };

    public static boolean contains(String[] array, String value) {
        for (String item : array)
            if (item.equals(value))
                return true;
        return false;
    }

    public static void main(String[] args) {
        String name = args[0];
        if (contains(catsNames, name)) {
            // В массиве содержится строка, которую пользователь
            // передал первым аргументом командной строки
        }
        else {
            // Строка не содержится в массиве
        }
    }
}

E
Eugene, 2018-04-24
@zolt85

Java 8 guys!

public static void main(String[] args) {
        String[] catsNames = new String[]{"Матроскин", "Барбос", "Пушистый п#$%рас"};

        boolean contains = Arrays.stream(cats).anyMatch("Матроскин"::equals);
        System.out.println(contains); //имеем true
        contains = Arrays.stream(cats).anyMatch("Барбоскин"::equals);
        System.out.println(contains); //имеем false
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question