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.
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 File
s 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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With