2017-03-09 37 views
0

列表检查数据我有对象的列表:存在的对象数组

List<Object[]> list = new ArrayList<>(); 
Object[] object = {"test", "test1", "test2"}; 
list.add(object); 

列表包含一些数据。

我有另一个字符串String str = "test";

我使用下面的代码。什么是最好的其他方式:

for (Object []object1 : list) { 
    for (Object obj : object1) { 
     if (obj.equals("test")) { 
      System.out.println("true"); 
     } 
    } 
} 

如何使用最少的代码检查此字符串目前在上面的列表中。

+0

简单使用包含()方法 – minigeek

回答

2

Java 8引入了Streams,它们功能强大,但代码紧凑。这个答案使用了Java 8的更多特性,如LambdasMethod References

这里是一个班轮指令:

boolean containsObject = list.stream().flatMap(Arrays::stream).filter(s->str.equals(s)).findFirst().isPresent(); 

这是如何工作的:

boolean containsObject = list.stream() // Turning the List into a Stream of Arrays 
    .flatMap(Arrays::stream)   // flattening the 2D structure into a single-dimensional stream of Objects (Note: using a Method reference) 
    .filter(s->str.equals(s))   // Filtering the flat stream to check for equality (Note: using a Lambda expression) 
    .findFirst()      // Demands to find the first Occurence that passed the Filter test 
    .isPresent();      // Collapse the stream and returns the result of the above demand (Note: the Stream makes no computation until this instruction) 

该解决方案是代码紧凑,并带来流的很好的特性,如并行和懒惰。

+1

虽然此代码片段可能会解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)真的有助于提高您的帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – DimaSan

0

如果您将Object[] s转换为列表,则可以调用它们的contains(Object)。您可以将list设置为List<List<Object>>,也可以将其设置为Object[]并根据需要将Object[]包装在List中。的

例的 “按需转换”:

for(Object[] object1 : list) 
    if(Arrays.asList(object1).contains("test")) 
     System.out.println("true"); 

就个人而言,我会list是一个List<List>。只要你添加它,只需将你的数组包装在一个列表中。假设arrObject[],这意味着list.add(Arrays.asList(arr));

亚历山大的答案也是正确的(我想;我没有仔细检查它),但是我发现长串流操作符的可读性较差。如果您不同意我的看法,请使用流操作符。