VMcPherron
VMcPherron

Reputation: 624

How can I remove entries from a List that match values from a Set

I'd like to do something similar to

Collection.removeAll(Set);

but I'm using a List<File> and Set<long>

I've got a List of Files, and I'd like to remove any file from the list that contains one of the longs in my set as part of the filename. I know I can do that if I iterate through the List of Files and do a compare to each entry in the set. But that sounds horribly inefficient.

Again, I'd like to create a List of Files that does NOT contain any of the longs in my Set as part of the filename.

(for example)

List<File> filesFromDirectory;
filesFromDirectory.add(new File("first.123.file"));
filesFromDirectory.add(new File("second.456.file"));

Set<Long> fnameVals = HashSet<Long>();
fnameVals.add(456);

...

I'd like the result to be:

System.out.println(filesFromDirectory);

first.123.file

Upvotes: 0

Views: 103

Answers (3)

Katriel
Katriel

Reputation: 123632

Disclaimer: I haven't written Java in aaaaages. This probably won't compile.

for(File f: filesFromDirectory) {
    bool OK = true;
    for(Long i: fnameVals) {
        if(f.name.contains(String.valueOf(i))) {
            OK = false;
            break;
    }
    if(OK) System.out.println(f.name);
}

Upvotes: 0

Geek
Geek

Reputation: 653

If your file names like : {chars}*[0-9] * {chars}* Number contained is unique(or you can implement a map algorithm for specific purpose)

How about this. Iterate over file names store them in hash map with key as the number and value as entire string. Iterate over set , for each value of set look in hash map, if object found remove it. Please see : it will work only in pattern defined and unique keys (which could be achieved) Also I am using iPad to answer so couldn't give answer in more details,sorry.. Don't like touchpad

Upvotes: 0

Ryan Shillington
Ryan Shillington

Reputation: 25097

Why don't you create a regular expression out of the Longs in your set and then match the filenames against the (single) regular expression?

Upvotes: 1

Related Questions