![](/img/trans.png)
[英]How to use Java Stream to check whether all data in a field in an list of objects are present in a field of a different object?
[英]Check data present in list of object array
我有一個對象列表:
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");
}
}
}
如何用最少的代碼檢查上面列表中的此字符串。
Java 8引入了Streams ,它們功能強大,但代碼緊湊,可滿足您的需求。 此答案使用了Java 8的更多功能,例如Lambdas和Method 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)
該解決方案代碼緊湊,並具有Streams的出色功能,例如並行化和惰性。
如果將Object[]
轉換為列表,則可以調用它們的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>
。 無論何時添加,只需將數組包裝在列表中即可。 假設arr
是一個Object[]
,則意味着list.add(Arrays.asList(arr));
。
Alexander的答案也是正確的(我認為;我沒有仔細研究過),但是我發現一長串的流運算符難以理解。 如果您不同意我的意見,請使用流運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.