代码之家  ›  专栏  ›  技术社区  ›  Mike Sickler

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

  •  2684
  • Mike Sickler  · 技术社区  · 16 年前

    我有一个 String[] 值如下:

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

    String s ,有没有好的方法来测试 VALUES 包含 s

    31 回复  |  直到 7 年前
        1
  •  2621
  •   Ray Hulha    7 年前
    Arrays.asList(yourArray).contains(yourValue)
    

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


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

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

    int[] a = {1,2,3,4};
    boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
    
        2
  •  325
  •   Craig P. Motlin    12 年前

    引用数组不正确。在这种情况下,我们追求的是一套。自Java SE 9以来,我们 Set.of .

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

    “给定字符串s,是否有一种好的方法来测试VALUES是否包含s?”

    VALUES.contains(s)
    

    正确类型 , 不可变的 , 简洁 很漂亮*

    原始答案详细信息

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

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

    (注意,你实际上可以放下 new String[];

    引用数组仍然很糟糕,我们需要一个集合:

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

    Collections.unmodifiableSet

    (*就品牌而言,集合API仍然缺少不可变的集合类型,语法对我来说仍然太冗长,这是可以预见的。)

        3
  •  185
  •   Intracer    10 年前

    您可以使用 ArrayUtils.contains Apache Commons Lang

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

    请注意,此方法返回 false 如果传递的数组是 null .

    例子:

    String[] fieldsToInclude = { "id", "name", "location" };
    
    if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
        // Do some stuff.
    }
    
        4
  •  148
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

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

    v != null 方法内部的条件是恒定的。在方法调用期间,它始终计算为相同的布尔值。因此,如果输入 array 如果是大的,只评估一次这个条件会更有效,我们可以在 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
  •  66
  •   Uri    11 年前

    Four Different Ways to Check If an Array Contains a Value

    1. List :

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

      public static boolean useSet(String[] arr, String targetValue) {
          Set<String> set = new HashSet<String>(Arrays.asList(arr));
          return set.contains(targetValue);
      }
      
    3. 使用一个简单的循环:

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

      binarySearch() 只能用于排序数组。 你会发现下面的结果很奇怪。这是对数组进行排序时的最佳选择。

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

    快速示例:

    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
    
        6
  •  63
  •   Gurwinder Singh    8 年前

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

    如果数组已排序,您可以进行二分查找,其中有一个 Arrays 类。

        7
  •  47
  •   camickr    16 年前

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

    使用10K阵列大小时,结果为:

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

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

    asList().contains

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

    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
  •  33
  •   assylias    12 年前

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

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

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

    STRINGS.contains("the string you want to find");
    
        9
  •  31
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

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

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

    public static <T> boolean arrayContains(T[] array, T value) {
        return Arrays.stream(array).anyMatch(value::equals);
    }
    
        10
  •  25
  •   GKFX    9 年前
        11
  •  16
  •   Tom Hawtin - tackline    16 年前

    ObStupid答案(但我认为这里有一个教训):

    enum Values {
        AB, BC, CD, AE
    }
    
    try {
        Values.valueOf(s);
        return true;
    } catch (IllegalArgumentException exc) {
        return false;
    }
    
        12
  •  12
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    在一个 数组:

    1. 哈希集
    2. asList
    3. 排序&;二进制

    1. 哈希集
    2. 二进制
    3. asList

        13
  •  10
  •   jhodges    13 年前

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

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

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

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

    第一个比第二个更易读。

        14
  •  9
  •   Pang Ajmal PraveeN    8 年前

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

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

    private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");
    
        15
  •  7
  •   Zar E Ahmer    12 年前

    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");
          }
      }
    }
    
        16
  •  6
  •   Shineed Basheer    11 年前

    使用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
  •  5
  •   Ryan    12 年前

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

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

    Programcreek

        18
  •  4
  •   Community Mohan Dere    9 年前

    最短的解决方案
    VALUES
    自从Java 9

    List.of(VALUES).contains(s);
    
        19
  •  3
  •   Pang Ajmal PraveeN    8 年前

    contains() ArrayUtils.in()

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

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

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

        20
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前
    1.  Arrays.asList(...).contains(...)
      
    2. 如果你反复检查一组更大的元素,可以获得更快的性能

      • 数组的结构不正确。使用 TreeSet 并将每个元素添加到其中。它对元素进行排序,并具有快速 exist()

      • Comparable &你想要 有序树 按顺序排序:

        ElementClass.compareTo() ElementClass.equals() Triads not showing up to fight? (Java Set missing an item)

        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));
        
      • 否则,请使用您自己的 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);
        
      • // Fast binary search through sorted elements (performance ~ log(size)):
        boolean containsElement = myElements.exists(someElement);
        
        21
  •  2
  •   Pang Ajmal PraveeN    8 年前

    如果你不想区分大小写

    Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
    
        22
  •  2
  •   TheArchon    7 年前

        String[] values = {"AB","BC","CD","AE"};
        String s = "A";
        boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));
    
        23
  •  2
  •   Akhil Babu Korkandi    7 年前

    试试这个:

    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");
    }
    
        24
  •  2
  •   Ruslan    7 年前

    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
        }
    }
    
        25
  •  -2
  •   mandy1339    8 年前

    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.
    }