How to check two arrays against each other using streams

Jaquarh :

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). 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.

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. 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.

Andrew Tobilko :

The problem is that you always return true from filter.

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. That array of Files could be mapped to file names by map(File::getName) and collect them into a set for further lookups.

Then, you would have the following

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70471&siteId=1