如何确定数组是否包含Java中的特定值?

时间:2021-09-12 20:46:26

I have a String[] with values like so:

我有一个String [],其值如下:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

Given String s, is there a good way of testing whether VALUES contains s?

鉴于String s,是否有一种测试VALUES是否包含s的好方法?

25 个解决方案

#1


Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).

警告:这不适用于基元数组(请参阅注释)。


Since you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

要检查int,double或long数组是否包含值,请分别使用IntStream,DoubleStream或LongStream。

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

#2


Just to clear the code up to start with. We have (corrected):

只是为了开始清除代码。我们已经(更正):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. It should be private:

这是一个可变的静态,FindBugs会告诉你这是非常顽皮的。它应该是私人的:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

(注意,你实际上可以删除新的String [];位。)

So, reference arrays are bad, and in particular here we want a set:

所以,参考数组很糟糕,特别是在这里我们需要一个集合:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could even be made public.)

(偏执狂的人,比如我自己,如果将它包装在Collections.unmodifiableSet中,可能会感到更放心 - 它甚至可以公开。)

"Given String s, is there a good way of testing whether VALUES contains s?"

“鉴于String,有没有一种很好的方法来测试VALUES是否包含s?”

VALUES.contains(s)

O(1).

#3


You can use ArrayUtils.contains from Apache Commons Lang

您可以使用Apache Commons Lang中的ArrayUtils.contains

public static boolean contains(Object[] array, Object objectToFind)

public static boolean contains(Object [] array,Object objectToFind)

Note that this method returns false if the passed array is null.

请注意,如果传递的数组为null,则此方法返回false。

There are also methods available for primitive arrays of all kinds.

还有适用于各种原始数组的方法。

Example:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}

#4


Just simply implement it by hand:

只需简单地手工实现:

public static <T> boolean contains(final T[] array, final T v) {
    for (final T e : array)
        if (e == v || v != null && v.equals(e))
            return true;

    return false;
}

Improvement:

The v != null condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for loop based on the result. The improved contains() method:

v!= null条件在方法内是常量。它始终在方法调用期间计算为相同的布尔值。因此,如果输入数组很大,那么仅评估此条件一次就更有效,并且我们可以根据结果在for循环内使用简化/更快的条件。改进的contains()方法:

public static <T> boolean contains2(final T[] array, final T v) {
    if (v == null) {
        for (final T e : array)
            if (e == null)
                return true;
    } 
    else {
        for (final T e : array)
            if (e == v || v.equals(e))
                return true;
    }

    return false;
}

#5


If the array is not sorted, you will have to iterate over everything and make a call to equals on each.

如果数组未排序,则必须迭代所有内容并在每个上调用equals。

If the array is sorted, you can do a binary search, there's one in the Arrays class.

如果数组已排序,您可以进行二进制搜索,Arrays类中有一个。

Generally speaking, if you are going to do a lot of membership checks, you may want to store everything in a Set, not in an array.

一般来说,如果要进行大量的成员资格检查,您可能希望将所有内容存储在Set中,而不是存储在数组中。

#6


Four Different Ways to Check If an Array Contains a Value

检查数组是否包含值的四种不同方法

1) Using List:

1)使用List:

public static boolean useList(String[] arr, String targetValue) {
    return Arrays.asList(arr).contains(targetValue);
}

2) Using Set:

2)使用Set:

public static boolean useSet(String[] arr, String targetValue) {
    Set<String> set = new HashSet<String>(Arrays.asList(arr));
    return set.contains(targetValue);
}

3) Using a simple loop:

3)使用简单的循环:

public static boolean useLoop(String[] arr, String targetValue) {
    for (String s: arr) {
        if (s.equals(targetValue))
            return true;
    }
    return false;
}

4) Using Arrays.binarySearch():

4)使用Arrays.binarySearch():

The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.

下面的代码是错误的,这里列出的是完整性。 binarySearch()只能用于排序数组。你会发现下面的结果很奇怪。这是排序数组时的最佳选择。

public static boolean binarySearch(String[] arr, String targetValue) {  
            int a = Arrays.binarySearch(arr, targetValue);
            return a > 0;
        }

Quick Example:

String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); // returns true
Arrays.asList(valueArray).contains(newValueNotInList); // returns false

#7


For what its worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().

为了它的价值,我进行了一项测试,比较了3个速度建议。我生成了随机整数,将它们转换为String并将它们添加到数组中。然后我搜索了最高可能的数字/字符串,这对于asList()。contains()来说是最糟糕的情况。

When using a 10K array size the results where:

使用10K数组大小时,结果如下:

Sort & Search   : 15
Binary Search   : 0
asList.contains : 0

When using a 100K array the results where:

使用100K阵列时,结果如下:

Sort & Search   : 156
Binary Search   : 0
asList.contains : 32

So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.

因此,如果数组是按排序顺序创建的,则二进制搜索是最快的,否则asList()。contains将是最佳选择。如果您有很多搜索,那么对数组进行排序可能是值得的,这样您就可以使用二进制搜索。这一切都取决于您的应用程序。

I would think those are the results most people would expect. Here is the test code:

我认为这些是大多数人所期望的结果。这是测试代码:

import java.util.*;

public class Test
{
    public static void main(String args[])
    {
        long start = 0;
        int size = 100000;
        String[] strings = new String[size];
        Random random = new Random();


        for (int i = 0; i < size; i++)
            strings[i] = "" + random.nextInt( size );

        start = System.currentTimeMillis();
        Arrays.sort(strings);
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
        System.out.println("Sort & Search : " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
        System.out.println("Search        : " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.asList(strings).contains( "" + (size - 1) ));
        System.out.println("Contains      : " + (System.currentTimeMillis() - start));
    }
}

#8


With Java 8 you can create a stream and check if any entries in the stream matches "s":

使用Java 8,您可以创建流并检查流中的任何条目是否与“s”匹配:

String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);

Or as a generic method:

或者作为通用方法:

public static <T> boolean arrayContains(T[] array, T value) {
    return Arrays.stream(array).anyMatch(value::equals);
}

#9


Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

您也可以使用Arrays.asList方法以类似的方式直接将其初始化为List,而不是使用快速数组初始化语法,例如:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

然后你可以做(​​如上所述):

STRINGS.contains("the string you want to find");

#10


You can use the Arrays class to perform a binary search for the value. If your array is not sorted, you will have to use the sort functions in the same class to sort the array, then search through it.

您可以使用Arrays类对该值执行二进制搜索。如果您的数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后搜索它。

#11


ObStupidAnswer (but I think there's a lesson in here somewhere):

ObStupidAnswer(但我认为这里有一个教训):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}

#12


Actually, if you use HashSet<String> as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.

实际上,如果您使用HashSet ,因为Tom Hawtin建议您不必担心排序,并且您的速度与预先排序的数组上的二进制搜索相同,可能更快。

It all depends on how your code is set up, obviously, but from where I stand, the order would be:

这一切都取决于您的代码的设置方式,显然,但从我的立场来看,订单将是:

On an unsorted array:

在未排序的数组上:

  1. HashSet
  2. asList
  3. sort & binary
  4. 排序和二进制

On a sorted array:

在排序的数组上:

  1. HashSet
  2. Binary
  3. asList

So either way, HashSet for the win.

无论哪种方式,HashSet为胜利。

#13


If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)

如果你有谷歌馆藏库,可以通过使用ImmutableSet(http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)简化汤姆的答案。

This really removes a lot of clutter from the initialization proposed

这确实消除了所提出的初始化中的大量混乱

private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");

#14


One possible solution:

一种可能的方案:

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

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}

#15


Developers often do:

开发人员经常这样做:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);

The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

上面的代码可以工作,但是不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以很简单:

Arrays.asList(arr).contains(targetValue);

or

   for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }

return false;

The first one is more readable than the second one.

第一个比第二个更可读。

#16


In Java 8 use Streams.

在Java 8中使用Streams。

List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

#17


Using a simple loop is the most efficient way of doing this.

使用简单的循环是最有效的方法。

boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}

Courtesy to Programcreek

由Programcreek提供

#18


  1. For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).

    对于有限长度的阵列,使用以下(由camickr给出)。重复检查的速度很慢,尤其是对于较长的阵列(线性搜索)。

     Arrays.asList(...).contains(...)
    
  2. For fast performance if you repeatedly check against a larger set of elements

    如果您反复检查更大的元素集,以获得快速性能

    • An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).

      数组是错误的结构。使用TreeSet并将每个元素添加到它。它对元素进行排序并具有快速exists()方法(二进制搜索)。

    • If the elements implement Comparable & you want the TreeSet sorted accordingly:

      如果元素实现Comparable并且您希望TreeSet相应地排序:

      ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)

      ElementClass.compareTo()方法必须与ElementClass.equals()兼容:看看Triads没有出现战斗? (Java Set缺少一个项目)

      TreeSet myElements = new TreeSet();
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
      // *Alternatively*, if an array is forceably provided from other code:
      myElements.addAll(Arrays.asList(myArray));
      
    • Otherwise, use your own Comparator:

      否则,请使用您自己的比较器:

      class MyComparator implements Comparator<ElementClass> {
           int compareTo(ElementClass element1; ElementClass element2) {
                // Your comparison of elements
                // Should be consistent with object equality
           }
      
           boolean equals(Object otherComparator) {
                // Your equality of comparators
           }
      }
      
      
      // construct TreeSet with the comparator
      TreeSet myElements = new TreeSet(new MyComparator());
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
    • The payoff: check existence of some element:

      收益:检查一些元素的存在:

      // Fast binary search through sorted elements (performance ~ log(size)):
      boolean containsElement = myElements.exists(someElement);
      

#19


Check this

String[] VALUES = new String[] {"AB","BC","CD","AE"};
String s;

for(int i=0; i< VALUES.length ; i++)
{
    if ( VALUES[i].equals(s) )
    { 
        // do your stuff
    } 
    else{    
        //do your stuff
    }
}

#20


Try this:

ArrayList<Integer> arrlist = new ArrayList<Integer>(8);

// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);

boolean retval = arrlist.contains(10);
if (retval == true) {
    System.out.println("10 is contained in the list");
}
else {
    System.out.println("10 is not contained in the list");
}

#21


Arrays.asList() -> then calling the contains() method will always work, but a search algorithm is much better since you don't need to create a lightweight list wrapper around the array, which is what Arrays.asList() does.

Arrays.asList() - >然后调用contains()方法将始终有效,但搜索算法要好得多,因为您不需要在数组周围创建一个轻量级的列表包装器,这就是Arrays.asList()所做的。

public boolean findString(String[] strings, String desired){
   for (String str : strings){
       if (desired.equals(str)) {
           return true;
       }
   }
   return false; //if we get here… there is no desired String, return false.
}

#22


Use the following (the contains() method is ArrayUtils.in() in this code):

使用以下(contains()方法是此代码中的ArrayUtils.in()):

ObjectUtils.java

public class ObjectUtils{

    /**
     * A null safe method to detect if two objects are equal.
     * @param object1
     * @param object2
     * @return true if either both objects are null, or equal, else returns false.
     */
    public static boolean equals(Object object1, Object object2){
        return object1==null ? object2==null : object1.equals(object2);
    }

}

ArrayUtils.java

public class ArrayUtils{

    /**
     * Find the index of of an object is in given array, starting from given inclusive index.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @param start  The index from where the search must start.
     * @return Index of the given object in the array if it is there, else -1.
     */
    public static <T> int indexOf(final T[] ts, final T t, int start){
        for(int i = start; i < ts.length; ++i)
            if(ObjectUtils.equals(ts[i], t))
                return i;
        return -1;
    }

    /**
     * Find the index of of an object is in given array, starting from 0;
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  indexOf(ts, t, 0)
     */
    public static <T> int indexOf(final T[] ts, final T t){
        return indexOf(ts, t, 0);
    }

    /**
     * Detect if the given object is in the given array.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  If indexOf(ts, t) is greater than -1.
     */
    public static <T> boolean in(final T[] ts, final T t){
        return indexOf(ts, t) > -1 ;
    }

}

As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

正如您在上面的代码中所看到的,还有其他实用程序方法ObjectUtils.equals()和ArrayUtils.indexOf(),它们也在其他地方使用过。

#23


If you don't want it to be case sensitive

如果您不希望它区分大小写

Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);

#24


Use Array.BinarySearch(array,obj) for finding the given object in array or not.

使用Array.BinarySearch(array,obj)来查找数组中的给定对象。

Example:

`if (Array.BinarySearch(str, i) > -1)` → true --exists

false --not exists

假 - 不存在

#25


Create a boolean initially set to false. Run a loop to check every value in the array and compare to the value you are checking against. If you ever get a match, set boolean to true and stop the looping. Then assert that the boolean is true.

创建一个最初设置为false的布尔值。运行循环以检查数组中的每个值,并与要检查的值进行比较。如果你得到一个匹配项,将boolean设置为true并停止循环。然后声明布尔值为true。

#1


Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).

警告:这不适用于基元数组(请参阅注释)。


Since you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

要检查int,double或long数组是否包含值,请分别使用IntStream,DoubleStream或LongStream。

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

#2


Just to clear the code up to start with. We have (corrected):

只是为了开始清除代码。我们已经(更正):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. It should be private:

这是一个可变的静态,FindBugs会告诉你这是非常顽皮的。它应该是私人的:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

(注意,你实际上可以删除新的String [];位。)

So, reference arrays are bad, and in particular here we want a set:

所以,参考数组很糟糕,特别是在这里我们需要一个集合:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could even be made public.)

(偏执狂的人,比如我自己,如果将它包装在Collections.unmodifiableSet中,可能会感到更放心 - 它甚至可以公开。)

"Given String s, is there a good way of testing whether VALUES contains s?"

“鉴于String,有没有一种很好的方法来测试VALUES是否包含s?”

VALUES.contains(s)

O(1).

#3


You can use ArrayUtils.contains from Apache Commons Lang

您可以使用Apache Commons Lang中的ArrayUtils.contains

public static boolean contains(Object[] array, Object objectToFind)

public static boolean contains(Object [] array,Object objectToFind)

Note that this method returns false if the passed array is null.

请注意,如果传递的数组为null,则此方法返回false。

There are also methods available for primitive arrays of all kinds.

还有适用于各种原始数组的方法。

Example:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}

#4


Just simply implement it by hand:

只需简单地手工实现:

public static <T> boolean contains(final T[] array, final T v) {
    for (final T e : array)
        if (e == v || v != null && v.equals(e))
            return true;

    return false;
}

Improvement:

The v != null condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for loop based on the result. The improved contains() method:

v!= null条件在方法内是常量。它始终在方法调用期间计算为相同的布尔值。因此,如果输入数组很大,那么仅评估此条件一次就更有效,并且我们可以根据结果在for循环内使用简化/更快的条件。改进的contains()方法:

public static <T> boolean contains2(final T[] array, final T v) {
    if (v == null) {
        for (final T e : array)
            if (e == null)
                return true;
    } 
    else {
        for (final T e : array)
            if (e == v || v.equals(e))
                return true;
    }

    return false;
}

#5


If the array is not sorted, you will have to iterate over everything and make a call to equals on each.

如果数组未排序,则必须迭代所有内容并在每个上调用equals。

If the array is sorted, you can do a binary search, there's one in the Arrays class.

如果数组已排序,您可以进行二进制搜索,Arrays类中有一个。

Generally speaking, if you are going to do a lot of membership checks, you may want to store everything in a Set, not in an array.

一般来说,如果要进行大量的成员资格检查,您可能希望将所有内容存储在Set中,而不是存储在数组中。

#6


Four Different Ways to Check If an Array Contains a Value

检查数组是否包含值的四种不同方法

1) Using List:

1)使用List:

public static boolean useList(String[] arr, String targetValue) {
    return Arrays.asList(arr).contains(targetValue);
}

2) Using Set:

2)使用Set:

public static boolean useSet(String[] arr, String targetValue) {
    Set<String> set = new HashSet<String>(Arrays.asList(arr));
    return set.contains(targetValue);
}

3) Using a simple loop:

3)使用简单的循环:

public static boolean useLoop(String[] arr, String targetValue) {
    for (String s: arr) {
        if (s.equals(targetValue))
            return true;
    }
    return false;
}

4) Using Arrays.binarySearch():

4)使用Arrays.binarySearch():

The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.

下面的代码是错误的,这里列出的是完整性。 binarySearch()只能用于排序数组。你会发现下面的结果很奇怪。这是排序数组时的最佳选择。

public static boolean binarySearch(String[] arr, String targetValue) {  
            int a = Arrays.binarySearch(arr, targetValue);
            return a > 0;
        }

Quick Example:

String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); // returns true
Arrays.asList(valueArray).contains(newValueNotInList); // returns false

#7


For what its worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().

为了它的价值,我进行了一项测试,比较了3个速度建议。我生成了随机整数,将它们转换为String并将它们添加到数组中。然后我搜索了最高可能的数字/字符串,这对于asList()。contains()来说是最糟糕的情况。

When using a 10K array size the results where:

使用10K数组大小时,结果如下:

Sort & Search   : 15
Binary Search   : 0
asList.contains : 0

When using a 100K array the results where:

使用100K阵列时,结果如下:

Sort & Search   : 156
Binary Search   : 0
asList.contains : 32

So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.

因此,如果数组是按排序顺序创建的,则二进制搜索是最快的,否则asList()。contains将是最佳选择。如果您有很多搜索,那么对数组进行排序可能是值得的,这样您就可以使用二进制搜索。这一切都取决于您的应用程序。

I would think those are the results most people would expect. Here is the test code:

我认为这些是大多数人所期望的结果。这是测试代码:

import java.util.*;

public class Test
{
    public static void main(String args[])
    {
        long start = 0;
        int size = 100000;
        String[] strings = new String[size];
        Random random = new Random();


        for (int i = 0; i < size; i++)
            strings[i] = "" + random.nextInt( size );

        start = System.currentTimeMillis();
        Arrays.sort(strings);
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
        System.out.println("Sort & Search : " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
        System.out.println("Search        : " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.asList(strings).contains( "" + (size - 1) ));
        System.out.println("Contains      : " + (System.currentTimeMillis() - start));
    }
}

#8


With Java 8 you can create a stream and check if any entries in the stream matches "s":

使用Java 8,您可以创建流并检查流中的任何条目是否与“s”匹配:

String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);

Or as a generic method:

或者作为通用方法:

public static <T> boolean arrayContains(T[] array, T value) {
    return Arrays.stream(array).anyMatch(value::equals);
}

#9


Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

您也可以使用Arrays.asList方法以类似的方式直接将其初始化为List,而不是使用快速数组初始化语法,例如:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

然后你可以做(​​如上所述):

STRINGS.contains("the string you want to find");

#10


You can use the Arrays class to perform a binary search for the value. If your array is not sorted, you will have to use the sort functions in the same class to sort the array, then search through it.

您可以使用Arrays类对该值执行二进制搜索。如果您的数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后搜索它。

#11


ObStupidAnswer (but I think there's a lesson in here somewhere):

ObStupidAnswer(但我认为这里有一个教训):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}

#12


Actually, if you use HashSet<String> as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.

实际上,如果您使用HashSet ,因为Tom Hawtin建议您不必担心排序,并且您的速度与预先排序的数组上的二进制搜索相同,可能更快。

It all depends on how your code is set up, obviously, but from where I stand, the order would be:

这一切都取决于您的代码的设置方式,显然,但从我的立场来看,订单将是:

On an unsorted array:

在未排序的数组上:

  1. HashSet
  2. asList
  3. sort & binary
  4. 排序和二进制

On a sorted array:

在排序的数组上:

  1. HashSet
  2. Binary
  3. asList

So either way, HashSet for the win.

无论哪种方式,HashSet为胜利。

#13


If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)

如果你有谷歌馆藏库,可以通过使用ImmutableSet(http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)简化汤姆的答案。

This really removes a lot of clutter from the initialization proposed

这确实消除了所提出的初始化中的大量混乱

private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");

#14


One possible solution:

一种可能的方案:

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

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}

#15


Developers often do:

开发人员经常这样做:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);

The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

上面的代码可以工作,但是不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以很简单:

Arrays.asList(arr).contains(targetValue);

or

   for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }

return false;

The first one is more readable than the second one.

第一个比第二个更可读。

#16


In Java 8 use Streams.

在Java 8中使用Streams。

List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

#17


Using a simple loop is the most efficient way of doing this.

使用简单的循环是最有效的方法。

boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}

Courtesy to Programcreek

由Programcreek提供

#18


  1. For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).

    对于有限长度的阵列,使用以下(由camickr给出)。重复检查的速度很慢,尤其是对于较长的阵列(线性搜索)。

     Arrays.asList(...).contains(...)
    
  2. For fast performance if you repeatedly check against a larger set of elements

    如果您反复检查更大的元素集,以获得快速性能

    • An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).

      数组是错误的结构。使用TreeSet并将每个元素添加到它。它对元素进行排序并具有快速exists()方法(二进制搜索)。

    • If the elements implement Comparable & you want the TreeSet sorted accordingly:

      如果元素实现Comparable并且您希望TreeSet相应地排序:

      ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)

      ElementClass.compareTo()方法必须与ElementClass.equals()兼容:看看Triads没有出现战斗? (Java Set缺少一个项目)

      TreeSet myElements = new TreeSet();
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
      // *Alternatively*, if an array is forceably provided from other code:
      myElements.addAll(Arrays.asList(myArray));
      
    • Otherwise, use your own Comparator:

      否则,请使用您自己的比较器:

      class MyComparator implements Comparator<ElementClass> {
           int compareTo(ElementClass element1; ElementClass element2) {
                // Your comparison of elements
                // Should be consistent with object equality
           }
      
           boolean equals(Object otherComparator) {
                // Your equality of comparators
           }
      }
      
      
      // construct TreeSet with the comparator
      TreeSet myElements = new TreeSet(new MyComparator());
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
    • The payoff: check existence of some element:

      收益:检查一些元素的存在:

      // Fast binary search through sorted elements (performance ~ log(size)):
      boolean containsElement = myElements.exists(someElement);
      

#19


Check this

String[] VALUES = new String[] {"AB","BC","CD","AE"};
String s;

for(int i=0; i< VALUES.length ; i++)
{
    if ( VALUES[i].equals(s) )
    { 
        // do your stuff
    } 
    else{    
        //do your stuff
    }
}

#20


Try this:

ArrayList<Integer> arrlist = new ArrayList<Integer>(8);

// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);

boolean retval = arrlist.contains(10);
if (retval == true) {
    System.out.println("10 is contained in the list");
}
else {
    System.out.println("10 is not contained in the list");
}

#21


Arrays.asList() -> then calling the contains() method will always work, but a search algorithm is much better since you don't need to create a lightweight list wrapper around the array, which is what Arrays.asList() does.

Arrays.asList() - >然后调用contains()方法将始终有效,但搜索算法要好得多,因为您不需要在数组周围创建一个轻量级的列表包装器,这就是Arrays.asList()所做的。

public boolean findString(String[] strings, String desired){
   for (String str : strings){
       if (desired.equals(str)) {
           return true;
       }
   }
   return false; //if we get here… there is no desired String, return false.
}

#22


Use the following (the contains() method is ArrayUtils.in() in this code):

使用以下(contains()方法是此代码中的ArrayUtils.in()):

ObjectUtils.java

public class ObjectUtils{

    /**
     * A null safe method to detect if two objects are equal.
     * @param object1
     * @param object2
     * @return true if either both objects are null, or equal, else returns false.
     */
    public static boolean equals(Object object1, Object object2){
        return object1==null ? object2==null : object1.equals(object2);
    }

}

ArrayUtils.java

public class ArrayUtils{

    /**
     * Find the index of of an object is in given array, starting from given inclusive index.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @param start  The index from where the search must start.
     * @return Index of the given object in the array if it is there, else -1.
     */
    public static <T> int indexOf(final T[] ts, final T t, int start){
        for(int i = start; i < ts.length; ++i)
            if(ObjectUtils.equals(ts[i], t))
                return i;
        return -1;
    }

    /**
     * Find the index of of an object is in given array, starting from 0;
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  indexOf(ts, t, 0)
     */
    public static <T> int indexOf(final T[] ts, final T t){
        return indexOf(ts, t, 0);
    }

    /**
     * Detect if the given object is in the given array.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  If indexOf(ts, t) is greater than -1.
     */
    public static <T> boolean in(final T[] ts, final T t){
        return indexOf(ts, t) > -1 ;
    }

}

As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

正如您在上面的代码中所看到的,还有其他实用程序方法ObjectUtils.equals()和ArrayUtils.indexOf(),它们也在其他地方使用过。

#23


If you don't want it to be case sensitive

如果您不希望它区分大小写

Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);

#24


Use Array.BinarySearch(array,obj) for finding the given object in array or not.

使用Array.BinarySearch(array,obj)来查找数组中的给定对象。

Example:

`if (Array.BinarySearch(str, i) > -1)` → true --exists

false --not exists

假 - 不存在

#25


Create a boolean initially set to false. Run a loop to check every value in the array and compare to the value you are checking against. If you ever get a match, set boolean to true and stop the looping. Then assert that the boolean is true.

创建一个最初设置为false的布尔值。运行循环以检查数组中的每个值,并与要检查的值进行比较。如果你得到一个匹配项,将boolean设置为true并停止循环。然后声明布尔值为true。