Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
Jaquarh Avatar asked Sep 29 '18 21:09

Jaquarh


1 Answers

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());
like image 138
Andrew Tobilko Avatar answered Nov 18 '22 23:11

Andrew Tobilko