我想创建一个方法来接收数据文件列表,然后在其中一个字段上使用字符串谓词对其进行过滤,并返回数据文件列表而不是字符串。
这是我的代码:
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>
上使用过滤器(即 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());
}
关于java - 使用字符串谓词过滤流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475308/