Comment déterminer si un tableau contient une valeur particulière en Java

Mots clés : javaarraysjava-8java

meilleur 5 Réponses Comment déterminer si un tableau contient une valeur particulière en Java

vote vote

94

Arrays.asList(yourArray).contains(yourValue) 
String[] values = {"AB","BC","CD","AE"}; boolean contains = Arrays.stream(values).anyMatch("s"::equals); 
int[] a = {1,2,3,4}; boolean contains = IntStream.of(a).anyMatch(x -> x == 4); 
vote vote

89

private static final Set<String> VALUES = Set.of(     "AB","BC","CD","AE" ); 
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"}; 
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(      new String[] {"AB","BC","CD","AE"} )); 
vote vote

75

String[] fieldsToInclude = { "id", "name", "location" };  if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {     // Do some stuff. } 
vote vote

70

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

50

public static boolean useList(String[] arr, String targetValue) {     return Arrays.asList(arr).contains(targetValue); } 
public static boolean useSet(String[] arr, String targetValue) {     Set<String> set = new HashSet<String>(Arrays.asList(arr));     return set.contains(targetValue); } 
public static boolean useLoop(String[] arr, String targetValue) {     for (String s: arr) {         if (s.equals(targetValue))             return true;     }     return false; } 
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 

Questions similaires