Как найти строку в массиве java

I want to search for a string in an arraylist.
My ArrayList contains:

ArrayList <String> list = new ArrayList(); 
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");

Now I want to search for "bea" and it should return a list containing "bear" and "beat".
How can I implement it?

PEHLAJ's user avatar

PEHLAJ

9,9409 gold badges40 silver badges52 bronze badges

asked Nov 19, 2011 at 7:39

Romi's user avatar

0

 List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           for (String string : list) {
               if(string.matches("(?i)(bea).*")){
                   listClone.add(string);
               }
           }
        System.out.println(listClone);

Community's user avatar

answered Nov 19, 2011 at 8:41

Abhishek's user avatar

AbhishekAbhishek

5753 silver badges5 bronze badges

3

Loop through your list and do a contains or startswith.

ArrayList<String> resList = new ArrayList<String>();
String searchString = "bea";

for (String curVal : list){
  if (curVal.contains(searchString)){
    resList.add(curVal);
  }
}

You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.

answered Nov 19, 2011 at 7:42

Udo Held's user avatar

Udo HeldUdo Held

12.3k11 gold badges67 silver badges93 bronze badges

1

Nowadays, Java 8 allows for a one-line functional solution that is cleaner, faster, and a whole lot simpler than the accepted solution:

List<String> list = new ArrayList<>();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");

List<String> matches = list.stream().filter(it -> it.contains("bea")).collect(Collectors.toList());

System.out.println(matches); // [bear, beat]

And even easier in Kotlin:

val matches = list.filter { it.contains("bea") }

answered Aug 26, 2016 at 0:13

sebnukem's user avatar

sebnukemsebnukem

8,0735 gold badges38 silver badges48 bronze badges

2

May be easier using a java.util.HashSet. For example:

  List <String> list = new ArrayList<String>(); 
  list.add("behold");
  list.add("bend");
  list.add("bet");

  //Load the list into a hashSet
  Set<String> set = new HashSet<String>(list);
  if (set.contains("bend"))
  {
    System.out.println("String found!");
  }

answered Jul 10, 2015 at 21:07

Marquez's user avatar

MarquezMarquez

5,8413 gold badges30 silver badges40 bronze badges

Since your list doesn’t appear to be sorted, you have to iterate over its elements. Apply startsWith() or contains() to each element, and store matches in an auxiliary list. Return the auxiliary list when done.

answered Nov 19, 2011 at 7:43

NPE's user avatar

NPENPE

483k108 gold badges944 silver badges1009 bronze badges

Better way is to use matches() method on every String element of the array. This will help you to search any pattern through regular expressions.

answered Nov 19, 2011 at 7:52

Drona's user avatar

DronaDrona

6,8081 gold badge28 silver badges35 bronze badges

The Best Order I’ve seen :

// SearchList is your List  
// TEXT is your Search Text
// SubList is your result

                    ArrayList<String> TempList = new ArrayList<String>(
                            (SearchList));
                    int temp = 0;
                    int num = 0;
                    ArrayList<String> SubList = new ArrayList<String>();
                    while (temp > -1) {
                        temp = TempList.indexOf(new Object() {
                            @Override
                            public boolean equals(Object obj) {
                                return obj.toString().startsWith(TEXT);
                            }
                        });
                        if (temp > -1) {
                         SubList.add(SearchList.get(temp + num++));
                         TempList.remove(temp);
                        }
                    }

answered Jul 23, 2014 at 6:31

Hamidreza Sadegh's user avatar

1

First you have to copy, from AdapterArrayList to tempsearchnewArrayList ( Add ListView items into tempsearchnewArrayList ) , because then only you can compare whether search text is appears in Arraylist or not.

After creating temporary arraylist, add below code.

    searchEditTextBox.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            String txt = charSequence.toString().trim();
            int txtlength = txt.length();
            if (txtlength > 0) {
                AdapterArrayList = new ArrayList<HashMap<String, String>>();
                for (int j = 0; j< tempsearchnewArrayList.size(); j++) {
                    if (tempsearchnewArrayList.get(j).get("type").toLowerCase().contains(txt)) {
                        AdapterArrayList.add(tempsearchnewArrayList.get(j));
                    }
                }
            } else {
                AdapterArrayList = new ArrayList<HashMap<String, String>>();
                AdapterArrayList.addAll(tempsearchnewArrayList);
            }
            adapter1.notifyDataSetChanged();
            if (AdapterArrayList.size() > 0) {
                mainactivitylistview.setAdapter(adapter1);
            } else {
                mainactivitylistview.setAdapter(null);
            }

        }
        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

answered Dec 16, 2016 at 12:41

Mani kandan's user avatar

Mani kandanMani kandan

3594 silver badges12 bronze badges

List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
           for (String string : list) {
               if(pattern.matcher(string).find()) {
                   listClone.add(string);
                   continue;
               }
           }
        System.out.println(listClone);

answered Mar 16, 2017 at 13:56

Rishabh's user avatar

RishabhRishabh

1,8271 gold badge12 silver badges9 bronze badges

2

TRY using Google guava library
FOR MORE INFO —> https://github.com/google/guava

Iterable<String> result = Iterables.filter(yourListContainStringsYouWantToSearch, Predicates.containsPattern(search));
Log.i("resultsInList", "performSearch:n"+ Lists.newArrayList(result.iterator()));

answered Oct 19, 2021 at 22:57

Adam reuben's user avatar

import java.util.*;
class ArrayLst
{
    public static void main(String args[])
    {
        ArrayList<String> ar = new ArrayList<String>();
        ar.add("pulak");
        ar.add("sangeeta");
        ar.add("sumit");
System.out.println("Enter the name:");
Scanner scan=new Scanner(System.in);
String st=scan.nextLine();
for(String lst: ar)
{
if(st.contains(lst))
{
System.out.println(st+"is here!");
break;
}
else
{
System.out.println("OOps search can't find!");
break;
}
}
}
}

answered May 12, 2014 at 8:38

Pulak's user avatar

PulakPulak

11 bronze badge

OK let’s say I have an array filled with {«tube», «are», «fun»} and then I have a JTextField and if I type either one of those commands to do something and if NOT to get like a message saying «Command not found».

I tried looking in Java docs but all I am getting is things that I don’t want like questions and stuff… so, how is this done? I know there is a «in array» function but I’m not too good with combining the two together.

Thanks.

Here is what I have so far:

String[] dan = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = dan.contains(say.getText());

but I am getting cannot find symbol in dan.contains

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

Вступление

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

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

  • Arrays.asList (). Contains ()
  • Использование цикла for
  • Collections.binarySearch ()
  • Java 8 Stream API
  • Apache Commons — ArrayUtils

Arrays.asList (). Contains ()

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

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

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

Массив Integer типа:

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

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

 false 
 true 

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

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

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

 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); 

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

 true 

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

 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); 

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

 false 

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

Это выведет:

 1 
 -6 

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

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

Java 8 Stream API

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

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

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

Это выведет:

 true 

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

 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); 

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

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

Оба они выведут:

 false 

Apache Commons — ArrayUtils

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

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

 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")); 

Это приведет к:

 true 
 true 

Заключение

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

В этом посте будет обсуждаться, как проверить, содержит ли массив определенное значение или нет в Java. Решение должно возвращать true, если массив содержит данный элемент; ложно в противном случае.

1. Использование промежуточного списка

Вы можете использовать Arrays.asList() чтобы получить список, поддерживаемый массивом, и вызвать List::contains метод, чтобы определить, присутствует ли значение в списке или нет.

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = Arrays.asList(values).contains(target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

 
Приведенное выше решение не работает для массивов примитивов. Если вы предпочитаете библиотеку Guava, используйте Ints.asList() метод для примитивов.

import com.google.common.primitives.Ints;

public class Main {

    public static void main(String[] args) {

        int[] values = {4, 3, 6, 8, 5};

        int target = 6;

        boolean found = Ints.asList(values).contains(target);

        System.out.println(found);        // true

    }

}

Скачать код

2. Использование промежуточного набора

Кроме того, вы можете создать набор из элементов массива и вызвать метод Set::contains способ определить, присутствует ли в нем заданное значение. Это показано ниже для массива String.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import java.util.Arrays;

import java.util.HashSet;

import java.util.Set;

public class Main {

    public static<T> boolean contains(T[] values, T target) {

        Set<T> set = new HashSet<>(Arrays.asList(values));

        return set.contains(target);

    }

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

 
Вот пример примитивных массивов с использованием Java 8 Stream:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import java.util.Arrays;

import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        int[] values = {5, 3, 4, 7, 6, 8};

        int target = 4;

        boolean found = Arrays.stream(values)

                            .boxed()

                            .collect(Collectors.toSet())

                            .contains(target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

3. Использование библиотеки Apache Commons Lang

Можно также использовать ArrayUtils.contains() метод, предлагаемый библиотекой Apache Commons Lang, который возвращает true, если массив содержит указанное значение. Он перегружен для всех типов примитивов и массивов объектов.

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = ArrayUtils.contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать код

4. Использование Stream.anyMatch() метод

В Java 8 и более поздних версиях вы можете создать поток и проверить, совпадают ли какие-либо элементы потока с заданным элементом, используя функцию anyMatch() метод. Это показано ниже для массива String:

import java.util.Arrays;

public class Main {

    public static<T> boolean contains(T[] values, T target) {

        return Arrays.stream(values).anyMatch(target::equals);

    }

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

 
Для примитивных массивов используйте == оператор для сопоставления с данным элементом.

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        int[] values = {5, 3, 2, 6, 3, 7};

        int target = 2;

        boolean found = Arrays.stream(values).anyMatch(i -> i == target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

5. Использование Stream.filter() метод

Другой подход заключается в преобразовать данный массив в поток и отфильтровать все вхождения указанного элемента с помощью filter() метод. Затем позвоните в findFirst() метод, возвращающий Optional.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.Arrays;

import java.util.Optional;

public class Main {

    public static<T> boolean contains(T[] values, T target) {

        return Arrays.asList(values).stream()

                .filter(x -> x.equals(target))

                .findFirst()

                .isPresent();

    }

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

 
Вы также можете позвонить в count() метод для получения количества указанного элемента в массиве:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import java.util.Arrays;

public class Main {

    public static<T> boolean contains(T[] values, T target) {

        return Arrays.asList(values).stream()

                .filter(x -> x.equals(target))

                .count() > 0;

    }

    public static void main(String[] args) {

        String[] values = {«B», «A», «C», «D», «E»};

        String target = «A»;

        boolean found = contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

 
Для примитивных массивов используйте == оператор для сравнения.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import java.util.Arrays;

public class Main {

    public static boolean contains(int[] values, int target) {

        return Arrays.stream(values)

                .filter(x -> x == target)

                .count() > 0;

    }

    public static void main(String[] args) {

        int[] values = {5, 3, 4, 7, 6, 8};

        int target = 4;

        boolean found = contains(values, target);

        System.out.println(found);        // true

    }

}

Скачать  Выполнить код

Это все о проверке, содержит ли массив определенное значение в Java.

Check if array contains value in java
This article will detail out 5 different methods to check if array contains a value in java with example programs.
Following are the methods to check the presence of a value in java array

We will be performing the following tasks :

  1. Check whether a string array contains a given string value.
  2. If the string exists in the array, then get the index of its position in array.

Method 1: Looping over the array
This is a conventional and most used method where the array of strings is iterated using a for loop and the value at every index is compared with the value to be searched in the array.
A boolean variable is set if any array value matches with the string. At the end of the loop, this boolean variable is checked to determine if the array contains the string.

public class ArrayContainsChecker { 
  public static void main(String[] args) { 
    methodOne(); 
  } 

  static void methodOne() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // initialize boolean variable 
    boolean isExists = false; 
    // iterate over array 
    for (int i = 0; i < array.length; i++) { 
      // get the value at current array index 
      String arrayValue = array[i]; 
      // compare values 
      if (valueToSearch.equals(arrayValue)) { 
        isExists = true; 
        // if value is found, terminate the loop 
        break; 
      } 
    } 
    if (isExists) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Use == operator to check for equality when comparing primitive types such as int, long, float, double etc.
Note that in this example, we are using a simple for loop with an index.
But, we may also use an enhanced for loop to iterate over the array, if we do not require the index of the value to check.

Method 2: Using List.contains()
Another method to check if an array contains an element is by using a list.
This method first converts the array to a java.util.List and then uses contains() method of java.util.List to check if the string exists in the list.

contains() method returns true if the value supplied as argument exists in the list and false otherwise. In other words, it checks if the list contains the supplied value.
Array is converted to a list using asList method of java.util.Arrays. This method takes an array as argument and returns a List with its elements populated with the contents of array.

import java.util.Arrays; 
import java.util.List; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodTwo(); 
  } 

  static void methodTwo() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // convert the array to a list 
    List list = Arrays.asList(array); 
    // check if string exists in list 
    if (list.contains(valueToSearch)) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Method 3: Using Apache Commons Library
This method utilizes ArrayUtils class from Apache Commons Library.
This class has a method contains() which takes two arguments : an array and a value. It searches for the value in the array and returns true if the value is found in the array, false otherwise.

import org.apache.commons.lang.ArrayUtils; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodThree(); 
  } 

  static void methodThree() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "three"; 
    // check if string exists in array 
    if (ArrayUtils.contains(array, valueToSearch)) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Apache Commons can be included using the following dependencies of Maven and Gradle. Use as per to the build tool suitable to you.

Maven

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

Gradle

compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

Method 4: Using Arrays.binarySearch()
java.util.Arrays has a binarySearch() method which searches for a value in an array using binary search algorithm.
This method takes two arguments :
1. an array, and
2. the item to search in the array
and returns the index of the item in the array.
It returns -1 if the element is not found in the array. Note that this method requires the array to be sorted before performing the search operation.

import java.util.Arrays; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodFour(); 
  } 

  static void methodFour() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "one"; 
    // sort the array 
    Arrays.sort(array); 
    // search the value and get its index 
    int index = Arrays.binarySearch(array, valueToSearch); 
    // if index is not -1 then value is present 
    if (index != -1) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Method 5: Java 8 anyMatch()
With java 8 stream you can directly get an element matching some value. For using streams, the array should be converted to a collection class.
Convert it to a java.util.List using asList() method of java.util.Arrays class.
On this list object call stream() method which returns a java.util.stream.Stream object.

Invoke anyMatch() method on this stream object. This method takes a java.util.function.Predicate object as argument.

A Predicate object can be created on the fly using java Lambda expression by writing an expression which returns a boolean value.

In the below example, the expression is s -> s.equals(valueToSearch). Here s represents the elements of array and compares them with the value we want to search in the array.
Thus the line list.stream().anyMatch(s -> s.equals(valueToSearch)) compares the elements of the list with the value to search and returns true if any element of the list matches the string in variable valueToSearch.

import java.util.Arrays; 
import java.util.List; 

public class StringChecker { 
  public static void main(String[] args) { 
    methodFive(); 
  } 

  static void methodFive() { 
    // initialize array 
    String[] array = { "one", "two", "three", "four" }; 
    // initialize value to search 
    String valueToSearch = "one"; 
    // convert the array to a list 
    List list = Arrays.asList(array); 
    // check if array contains value 
    boolean isFound = list.stream().anyMatch(s -> s.equals(valueToSearch)); 
    if (isFound) { 
      System.out.println("String is found in the array"); 
    } else { 
      System.out.println("String is not found in the array"); 
    } 
  } 
}

Output

String is found in the array

Let’s tweak in

  1. binarySearch() method will return -1 even if the value is present in the array if the array is not sorted.
  2. binarySearch() method can also be used directly in situations when the index of the value in the array is required.
  3. Arrays.asList will throw a java.lang.NullPointerException if the array supplied as argument is null.
  4. ArrayUtils from Apache Commons library also iterates over the array and compares each element with the value to search.
  5. There are different overloaded versions of contains method in ArrayUtils from Apache Commons library which act on arrays of various data types such as char, float, double, int, long, short etc.
  6. All the above methods work on string arrays but they can be used to search an element in array of other data types such as int array, char array etc.

Hope the article was useful.

Понравилась статья? Поделить с друзьями:
  • Как составить смету на строительство деревянных домов
  • Как найти хороший унитаз
  • Как найти доступ к порту
  • Как найти клиентов иностранцев
  • Как найти среднюю стоимость единицы товара