简体   繁体   English

如何使用流检查两个阵列

[英]How to check two arrays against each other using streams

I have an array list of apps, I have a directory which will only contain jar files (I am using reflection to access these jar files in my platform). 我有一个应用程序的数组列表,我有一个目录,它只包含jar文件(我使用反射来访问我平台中的这些jar文件)。 I want to loop through all of the files inside the directory, find all of the jar files and then check that they are part of the array list of verified apps and from that, build a new array list of all the ones that are verified and exist. 我想循环遍历目录中的所有文件,查找所有jar文件,然后检查它们是已验证应用程序的数组列表的一部分,并从中构建一个新的数组列表,其中包含所有已验证的和存在。

So far, I have this: 到目前为止,我有这个:

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

However, this is giving me everything inside of the arraylist even if they do not exist in file. 但是,这给了我arraylist里面的所有内容,即使它们不存在于文件中。 Any help would be appreciated and I want to use a stream. 任何帮助将不胜感激,我想使用流。

I would like to turn this: 我想转此:

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

Into using a stream to get used to knowing how to use streams. 使用流来习惯了解如何使用流。

The problem is that you always return true from filter . 问题是你总是从filter返回true

File[] listOfFiles = new File("C:/Temp/MyApps/").listFiles();
Set<String> filesNames = Arrays.stream(listOfFiles)
                               .map(File::getName)
                               .collect(Collectors.toSet());

This could be moved outside the filter lambda to avoid creating a File[] for each app. 这可以移到filter lambda之外,以避免为每个应用程序创建File[] That array of File s could be mapped to file names by map(File::getName) and collect them into a set for further lookups. 可以通过map(File::getName)File数组映射到文件名,并将它们收集到一个集合中以供进一步查找。

Then, you would have the following 然后,您将拥有以下内容

List<Application> verifiedApps = 
    App.getAppStore()
       .stream()
       .filter(o -> filesNames.contains(o.getName() + ".jar"))
       .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM