我想制作一个接收DataFiles列表的方法,然后在其字段之一上使用String谓词对其进行过滤,然后返回DataFiles列表,而不是String。

这是我的代码:

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();
}

当我执行.map(DataFile::getFileName)时,我将流转换为Stream<String>,但我想将其保留为Stream<DataFile>,但仍对该Predicate<String>使用filter(即DataFile::getFileName)。那可能吗?

最佳答案

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());
}

09-04 04:42