如何使用字符串过滤我的列表?

Eri*_*tov 2 java collections java-stream

有人可以解释我为什么我不能在List by .stream()中过滤我的字符串.过滤器?我收到的只是未经过滤的字符串!我会很感激的.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mạn*_*yễn 7

你忽略了collect的结果:

countries.stream().filter(s -> s.getName().contains("xx"))
         .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

因此,您应该将结果分配给新列表并仅打印该列表

List<Country> result = countries.stream()...
result.forEach(...)
Run Code Online (Sandbox Code Playgroud)