[英]filter array with another all array elements - Java 8
我有一個像這樣的字符串數組:
firstArray = {"1", "2", "3", "4" };
我有這樣的第二個數組:
secondArray = {"2", "5", "6", "7" };
如果我想流一個元素,我可以這樣做:
firstArray.stream()
.filter(element -> !element.equals("2"))
.forEach((element) -> {
finalArrayList.add(element);
}
);
我如何在Java 8中流式傳輸第一個數組和第二個數組的所有元素?
如果要使用Stream API
僅將第一個數組中沒有的元素保留在第二個數組中,則可以這樣進行:
List<String> result = Arrays.stream(firstArray)
.filter(el -> Arrays.stream(secondArray).noneMatch(el::equals))
.collect(Collectors.toList());
您到底想做什么? 獲取第二個數組中也存在的第一個數組中的所有元素?
像這樣:
String[] firstArray = {"1", "2", "3", "4"};
String[] secondArray = {"2", "5", "6", "7"};
List<String> finalArrayList = Arrays.stream(firstArray)
.filter(element -> arrayContains(secondArray, element))
.collect(Collectors.toList());
使用以下實用程序方法:
public static <T> boolean arrayContains(T[] array, T element) {
return Arrays.stream(array)
.filter(e -> e.equals(element))
.findFirst().isPresent();
}
注意:不要使用forEach
並將結果添加到finalArrayList
,而應使用收集器。 從功能編程的角度來看,這是更純粹的。
編輯 -具有Holger的技巧(請參閱下面的評論):
public static <T> boolean arrayContains(T[] array, T element) {
return Arrays.stream(array)
.anyMatch(e -> e.equals(element));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.