Filtering a stream using String predicate

Viewed 81

I want to make a method that receives List of DataFiles then filters it using String predicate on one of its fields and returns List of DataFiles instead of Strings.

Here is my code:

public static List<DataFile> someMethod(List<DataFile> dataFiles) {
    return dataFiles
            .stream()
            .map(DataFile::getFileName)
            .filter(companyAndDateFilter(date, BLABLA, LALALA))
            .collect(Collectors.toList());
}

private static Predicate<String> companyAndDateFilter(LocalDate date, String... companyNames) {
    String companies = getCompaniesAsString(companyNames);
    String formattedDate = formatTheDate(date);
    Pattern pattern =  Pattern
            .compile("^(" + companies + ")_(" + formattedDate + ")");
    LOGGER.info("Filtering files using RegEx: " + pattern.pattern());
            return pattern.asPredicate();
}

When I do .map(DataFile::getFileName) I transform my stream into Stream<String> but I would like to leave it as Stream<DataFile> and still use filter (which is Predicate<String>) on that DataFile::getFileName. Is that possible?

1 Answers
public static List<DataFile> someMethod(List<DataFile> dataFiles) {
    Predicate<String> hasCompanyAndDate = companyAndDateFilter(date, BLABLA, LALALA);

    return dataFiles.stream()
        .filter(dataFile -> hasCompanyAndDate.test(dataFile.getFileName()))
        .collect(Collectors.toList());
}
Related