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

标签 java collections java-stream

有人可以解释一下为什么我无法通过 .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/

相关文章:

java - 使用 Parse 从应用程序引擎发送推送通知

java - Drools acquire() 的空指针异常

java - Hamcrest 匹配器的冲突重载

java - addAll to Set 不在 java 中添加值

java - 并发收集到 50/50 读/写

java - 为什么Stream <T> collect方法返回不同的键顺序?

java - 使用 Swig 将 Java 对象传递给 C++...然后返回给 Java

javascript - 清除 map 是否有助于垃圾收集?

java - 使用 Java 8 中的 lambda 函数获取 ArrayList 的总数,根据日期分组

java - 是否可以仅同步 java 流中的终端方法调用?