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

w8ntj3qf  于 2021-07-09  发布在  Java
关注(0)|答案(29)|浏览(368)

我有一个 String[] 价值观如下:

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

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

rsl1atfo

rsl1atfo1#

Arrays.asList(yourArray).contains(yourValue)

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

由于java-8,您现在可以使用流了。

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

3okqufwl2#

如果我的数组包含重复项,则为最短解决方案
自java 9以来

List.of(VALUES).contains(s);
9avjhtql

9avjhtql3#

由于我正在使用基本类型byte和byte[]处理低级java,所以到目前为止,我得到的最好的结果是bytes-javahttps://github.com/patrickfav/bytes-java 似乎是个好作品

20jt8wwn

20jt8wwn4#

使用Java8,您可以创建一个流并检查流中是否有匹配的条目 "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);
}
ilmyapht

ilmyapht5#

不必使用快速数组初始化语法,您可以直接使用arrays.aslist方法以类似的方式将其初始化为列表,例如:

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

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

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

icnyk63a6#

对于长度有限的数组,请使用以下命令(由camickr给出)。这对于重复检查来说很慢,尤其是对于较长的数组(线性搜索)。

Arrays.asList(...).contains(...)

如果您反复检查一组较大的元素,则可以获得快速性能
数组是错误的结构。使用 TreeSet 并将每个元素添加到其中。它对元素进行排序并具有快速响应 exist() 方法(二进制搜索)。
如果元素实现 Comparable &你想要那个 TreeSet 相应排序: ElementClass.compareTo() 方法必须与兼容 ElementClass.equals() :看到三合会没有出现打架吗(java集(缺少项)

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

tpgth1q77#

使用以下方法 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 ;
    }

}

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

relj7zay

relj7zay8#

使用 Array.BinarySearch(array,obj) 是否在数组中查找给定对象。
例子:

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

false—不存在

fdx2calv

fdx2calv9#

试试这个:

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

yqlxgs2m10#

如果数组没有排序,您将不得不遍历所有内容并在每个数组上调用equals。
如果数组被排序,你可以做一个二进制搜索,在arrays类中有一个。
一般来说,如果要进行大量的成员资格检查,可能需要将所有内容存储在一个集合中,而不是存储在一个数组中。

piok6c0g

piok6c0g11#

javase9的简明更新

引用数组不正确。对于这个案子,我们要找的是一套。自从JavaSE9以来 Set.of .

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

给定字符串s,有没有一种测试值是否包含s的好方法

VALUES.contains(s)

o(1)。
正确的类型,不可变,o(1)且简洁。很漂亮*

原始答案详细信息

首先要清除代码。我们已(更正):

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

这是一个可变的静态findbugs会告诉你是非常淘气。不要修改静态,也不要允许其他代码这样做。该字段至少应为私有字段:

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 -甚至可以公开。)
(*对于品牌来说,collections api仍然缺少不可变的集合类型,语法仍然过于冗长,这是可以预见的

tct7dpnv

tct7dpnv12#

如果你有googlecollections库,tom的答案可以通过使用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");
lzfw57am

lzfw57am13#

一种可能的解决方案:

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

ojsjcaue14#

在Java8中使用流。

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

moiiocjp15#

看看这个

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

相关问题