有人可以解释一下为什么我无法通过 .stream().filter 过滤列表中的字符串吗?我收到的只是未经过滤的字符串! 我会很感激的。
public static void main(String[] args) throws FileNotFoundException {
List<Country> countries = CsvToBeanConverterCountry("country.csv");
countries
.stream().filter(s -> s.getName().contains("xx")).collect(Collectors.toList());
countries.forEach(s -> System.out.println(s.getName()));
}
private static List CsvToBeanConverterCountry(String csvFilename) throws FileNotFoundException {
CsvToBean csv = new CsvToBean();
CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ';', '"', 1);
List list = csv.parse(setColumMappingCountry(), csvReader);
return list;
}
private static ColumnPositionMappingStrategy setColumMappingCountry() {
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(Country.class);
String[] columns = new String[]{"country_id", "city_id", "name"};
strategy.setColumnMapping(columns);
return strategy;
}
}
最佳答案
您忽略了收集的结果:
countries.stream().filter(s -> s.getName().contains("xx"))
.collect(Collectors.toList());
因此您应该将结果分配给一个新列表并仅打印该列表
List<Country> result = countries.stream()...
result.forEach(...)
关于java - 如何用字符串过滤我的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934828/