How do I determine whether an array contains a particular value in Java?

后端 未结 29 2802
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

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

Given

相关标签:
29条回答
  • 2020-11-21 05:33

    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.

    0 讨论(0)
  • 2020-11-21 05:33

    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");
          }
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:34

    Four Different Ways to Check If an Array Contains a Value

    1. Using List:

      public static boolean useList(String[] arr, String targetValue) {
          return Arrays.asList(arr).contains(targetValue);
      }
      
    2. Using 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:

      public static boolean useLoop(String[] arr, String targetValue) {
          for (String s: arr) {
              if (s.equals(targetValue))
                  return true;
          }
          return false;
      }
      
    4. Using 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.

      public static boolean binarySearch(String[] arr, String targetValue) {  
          return Arrays.binarySearch(arr, targetValue) >= 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
    
    0 讨论(0)
  • 2020-11-21 05:34

    Try using Java 8 predicate test method

    Here is a full example of it.

    import java.util.Arrays;
    import java.util.List;
    import java.util.function.Predicate;
    public class Test {
     public static final List<String> VALUES = Arrays.asList("AA", "AB", "BC", "CD", "AE");
    
     public static void main(String args[]) {
      Predicate<String> containsLetterA = VALUES -> VALUES.contains("AB");
      for (String i : VALUES) {
    
       System.out.println(containsLetterA.test(i));
      } 
     }
    }
    

    http://mytechnologythought.blogspot.com/2019/10/java-8-predicate-test-method-example.html

    https://github.com/VipulGulhane1/java8/blob/master/Test.java

    0 讨论(0)
  • 2020-11-21 05:35
    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).

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

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

        ElementClass.compareTo() method must be compatable with ElementClass.equals(): see 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));
        
      • 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);
        
    0 讨论(0)
  • 2020-11-21 05:37

    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)

    This really removes a lot of clutter from the initialization proposed

    private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");
    
    0 讨论(0)
提交回复
热议问题