Проверить наличие элемента массива java

Java: Check if Array Contains Value or Element

Whether in Java, or any other programming language, it is a common occurrence to check if an array contains a value. This is one of the things that most beginners tend to learn, and it is a useful thing to know in general.

In this article, we’ll take a look at how to check if an array contains a value or element in Java.

Arrays.asList().contains()

This is perhaps the most common way of solving this problem, just because it performs really well and is easy to implement.

First, we convert the array to an ArrayList . There are various ways to convert a Java array to an ArrayList, though, we’ll be using the most widely used approach.

Then, we can use the contains() method on the resulting ArrayList , which returns a boolean signifying if the list contains the element we’ve passed to it or not.

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(intList.contains(12)); System.out.println(nameList.contains("John")); 

Running this code results in:

Using a for-loop

A more basic and manual approach to solving the problem is by using a for loop. In worst case, it’ll iterate the entire array once, checking if the element is present.

Let’s start out with primitive integers first:

int[] intArray = new int[]1, 2, 3, 4, 5>; boolean found = false; int searchedValue = 2; for(int x : intArray)< if(x == searchedValue)< found = true; break; > > System.out.println(found); 

The found variable is initially set to false because the only way to return true would be to find the element and explicitly assign a new value to the boolean. Here, we simply compare each element of the array to the value we’re searching for, and return true if they match:

For Strings, and custom Objects you might have in your code, you’d be using a different comparison operator. Assuming you’ve validly ovverriden the equals() method, you can use it to check if an object is equal to another, returning true if they are:

String[] stringArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; boolean found = false; String searchedValue = "Michael"; for(String x : stringArray)< if(x.equals(searchedValue))< found = true; break; > > System.out.println(found); 

Running this code will result in:

Читайте также:  Замок раннего реагирования питон

Collections.binarySearch()

Additionally, we can find a specific value using a built-in method binarySearch() from the Collections class. The problem with binary search is that it requires our array be sorted. If our array is sorted though, binarySearch() outperforms both the Arrays.asList().contains() and the for-loop approaches.

If it’s not sorted, the added time required to sort the array might make this approach less favorable, depending on the size of the array and the sorting algorithm used to sort it.

binarySearch() has many overloaded variants depending on the types used and our own requirements, but the most general one is:

public static int binarySearch(Object[] a, Object[] key) 

Where a represents the array, and key the specified value we’re looking for.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Now, the return value might be a bit confusing, so it’s best to take Oracle’s official documentation in mind:

The return value of this method is the index of the searched key, if it is contained in the array; otherwise (-(insertion point) — 1), where insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"Bill", "Connor", "Joe", "John", "Mark">; // Array is already sorted lexicographically List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(Collections.binarySearch(intList, 2)); System.out.println(Collections.binarySearch(nameList, "Robin")); 

The first element is found, at position 1 . The second element isn’t found, and would be inserted at position 5 — at the end of the array. The return value is -(insertion point)-1 , so the return value ends up being -6 .

If the value is above equal to, or above 0 , the array contains the element, and it doesn’t contain it otherwise.

Java 8 Stream API

The Java 8 Stream API is very versatile and offers for concise solutions to various tasks related to processing collections of objects. Using Streams for this type of task is natural and intuitive for most.

Let’s take a look at how we can use the Stream API to check if an array contains an integer:

Integer[] arr = new Integer[]1, 2, 3, 4, 5>; System.out.println(Arrays.stream(arr).anyMatch(x -> x == 3)); 

And to do this with Strings or custom objects:

String[] arr = new String[]"John", "Mark", "Joe", "Bill", "Connor">; String searchString = "Michael"; boolean doesContain = Arrays.stream(arr) .anyMatch(x -> x.equals(searchString)); System.out.println(doesContain); 

Or, you can make this shorter by using a method reference:

boolean doesContain = Arrays.stream(arr) .anyMatch(searchString::equals); System.out.println(doesContain); 

Both of these would output:

Читайте также:  Number squared in javascript

Apache Commons — ArrayUtils

The Apache Commons library provides many new interfaces, implementations and classes that expand on the core Java Framework, and is present in many projects.

The ArrayUtils class introduces many methods for manipulating arrays, including the contains() method:

Integer[] intArray = new Integer[]1, 2, 3, 4, 5>; String[] nameArray = new String[]"John", "Mark", "Joe", "Bill", "Connor">; System.out.println(ArrayUtils.contains(intArray, 3)); System.out.println(ArrayUtils.contains(nameArray, "John")); 

Conclusion

In this article, we’ve gone over several ways to check whether an array in Java contains a certain element or value. We’ve gone over converting the array to a list and calling the contains() method, using a for-loop, the Java 8 Stream API, as well as Apache Commons.

Источник

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Java: проверьте, содержит ли массив значение или элемент

Введение В Java или на любом другом языке программирования обычно проверяют, содержит ли массив значение. Это одна из вещей, которую обычно усваивают новички, и в целом это полезно знать. В этой статье мы рассмотрим, как проверить, содержит ли массив значение или элемент в Java. * Arrays.asList (). Contains () * Использование цикла for * Collections.binarySearch () * API потока Java 8 * Apache Commons — ArrayUtils Arrays.asList (). Contains () T

Вступление

Будь то Java или любой другой язык программирования, обычно проверяют, содержит ли массив значение. Это одна из вещей, которую обычно усваивают новички, и в целом это полезно знать.

В этой статье мы рассмотрим, как проверить, содержит ли массив значение или элемент в Java .

Arrays.asList (). Contains ()

Это, пожалуй, самый распространенный способ решения этой проблемы просто потому, что он работает очень хорошо и его легко реализовать.

Сначала мы конвертируем массив в ArrayList . Существуют различные способы преобразования массива Java в ArrayList , однако мы будем использовать наиболее широко используемый подход.

Затем мы можем использовать метод contains() для результирующего ArrayList , который возвращает логическое значение, указывающее, содержит ли список переданный нам элемент или нет.

 Integer[] intArray = new Integer[]; String[] nameArray = new String[]; List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(intList.contains(12)); System.out.println(nameList.contains("John")); 

Выполнение этого кода приводит к:

Использование цикла for

Более простой и ручной подход к решению проблемы — использование цикла for В худшем случае он выполнит итерацию по всему массиву один раз, проверяя, присутствует ли элемент.

Начнем сначала с примитивных целых чисел:

 int[] intArray = new int[]; boolean found = false; int searchedValue = 2; for(int x : intArray) < if(x == searchedValue)< found = true; break; >> System.out.println(found); 

Для found переменной изначально установлено значение false потому что единственный способ вернуть true это найти элемент и явно присвоить новое значение логическому элементу. Здесь мы просто сравниваем каждый элемент массива со значением, которое ищем, и возвращаем true если они совпадают:

Для строк и настраиваемых объектов, которые могут быть в вашем коде, вы должны использовать другой оператор сравнения. Предполагая, что вы действительно переопределили метод equals() , вы можете использовать его, чтобы проверить, равен ли объект другому, возвращая true если они:

 String[] stringArray = new String[]; boolean found = false; String searchedValue = "Michael"; for(String x : stringArray) < if(x.equals(searchedValue))< found = true; break; >> System.out.println(found); 

Выполнение этого кода приведет к:

Читайте также:  Java find element in xml

Collections.binarySearch ()

Кроме того, мы можем найти конкретное значение, используя встроенный метод binarySearch() из класса Collections Проблема с двоичным поиском в том, что он требует сортировки нашего массива. Если наш массив отсортирован , хотя, binarySearch() превосходит как Arrays.asList().contains() и для петли подходов.

Если он не отсортирован, дополнительное время, необходимое для сортировки массива, может сделать этот подход менее выгодным, в зависимости от размера массива и алгоритма сортировки, используемого для его сортировки.

binarySearch() имеет много перегруженных вариантов в зависимости от используемых типов и наших собственных требований, но наиболее общий из них:

 public static int binarySearch(Object[] a, Object[] key) 

Где a представляет массив, и key указанное значение, которое мы ищем.

Теперь возвращаемое значение может немного сбивать с толку, поэтому лучше иметь в виду официальную документацию Oracle:

Возвращаемое значение этого метода — индекс искомого ключа, если он содержится в массиве; в противном случае (- ( точка вставки ) — 1), где точка вставки определяется как точка, в которой ключ будет вставлен в массив: индекс первого элемента больше, чем ключ, или a.length если все элементы в массив меньше указанного ключа.

 Integer[] intArray = new Integer[]; String[] nameArray = new String[]; // Array is already sorted lexicographically List intList = new ArrayList<>(Arrays.asList(intArray)); List nameList = new ArrayList<>(Arrays.asList(nameArray)); System.out.println(Collections.binarySearch(intList, 2)); System.out.println(Collections.binarySearch(nameList, "Robin")); 

Первый элемент находится в позиции 1 . Второй элемент не найден и будет вставлен в позицию 5 — в конец массива. Возвращаемое значение -(insertion point)-1 , поэтому возвращаемое значение оказывается -6 .

Если значение больше или равно 0 , массив содержит элемент, в противном случае он не содержит его.

Java 8 Stream API

Java 8 Stream API очень универсален и предлагает краткие решения различных задач, связанных с обработкой коллекций объектов. Для большинства задач использование Streams является естественным и интуитивно понятным.

Давайте посмотрим, как мы можем использовать Stream API, чтобы проверить, содержит ли массив целое число:

 Integer[] arr = new Integer[]; System.out.println(Arrays.stream(arr).anyMatch(x -> x == 3)); 

И чтобы сделать это со строками или настраиваемыми объектами:

 String[] arr = new String[]; String searchString = "Michael"; boolean doesContain = Arrays.stream(arr) .anyMatch(x -> x.equals(searchString)); System.out.println(doesContain); 

Или вы можете сделать это короче, используя ссылку на метод:

 boolean doesContain = Arrays.stream(arr) .anyMatch(searchString::equals); System.out.println(doesContain); 

Apache Commons — ArrayUtils

Библиотека Apache Commons предоставляет множество новых интерфейсов, реализаций и классов, расширяющих базовую платформу Java Framework, и присутствует во многих проектах.

Класс ArrayUtils представляет множество методов для управления массивами, включая метод contains() :

 Integer[] intArray = new Integer[]; String[] nameArray = new String[]; System.out.println(ArrayUtils.contains(intArray, 3)); System.out.println(ArrayUtils.contains(nameArray, "John")); 

Заключение

В этой статье мы рассмотрели несколько способов проверить, содержит ли массив в Java определенный элемент или значение. Мы рассмотрели преобразование массива в список и вызов contains() с использованием цикла for, Java 8 Stream API, а также Apache Commons.

Licensed under CC BY-NC-SA 4.0

Источник

Оцените статью