[英]How to check two arrays against each other using streams
我有一個應用程序的數組列表,我有一個目錄,它只包含jar文件(我使用反射來訪問我平台中的這些jar文件)。 我想循環遍歷目錄中的所有文件,查找所有jar文件,然后檢查它們是已驗證應用程序的數組列表的一部分,並從中構建一個新的數組列表,其中包含所有已驗證的和存在。
到目前為止,我有這個:
App.getAppStore()
.stream()
.filter(o -> {
File[] listOfFiles = new File("C:/Temp/MyApps/").listFiles();
Object[] foo = Arrays.stream(listOfFiles)
.filter(x -> x.getName().contains(o.getName()))
.toArray();
return true;
}).toArray();
但是,這給了我arraylist里面的所有內容,即使它們不存在於文件中。 任何幫助將不勝感激,我想使用流。
我想轉此:
ArrayList<Application> verifiedApps = new ArrayList<verifiedApps>();
for( Application app : App.getAppStore() ) {
for( File verifiedApp : new File("C:/Temp/MyApps/").listFiles() ) {
if( verifiedApp.getName().contains( app.getName() )
verifiedApps.add( app );
}
}
使用流來習慣了解如何使用流。
問題是你總是從filter
返回true
。
File[] listOfFiles = new File("C:/Temp/MyApps/").listFiles();
Set<String> filesNames = Arrays.stream(listOfFiles)
.map(File::getName)
.collect(Collectors.toSet());
這可以移到filter
lambda之外,以避免為每個應用程序創建File[]
。 可以通過map(File::getName)
將File
數組映射到文件名,並將它們收集到一個集合中以供進一步查找。
然后,您將擁有以下內容
List<Application> verifiedApps =
App.getAppStore()
.stream()
.filter(o -> filesNames.contains(o.getName() + ".jar"))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.