Reputation: 21
Could someone explain me why I can`t filter my strings in List by .stream().filter ? All I receive is unfiltered strings! I will appreciate it.
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;
}
}
Upvotes: 2
Views: 126
Reputation: 269867
It seems like your intent was to modify the original list, rather than to produce a new list with some of the elements.
In that case, you can simply remove the elements you don't want:
countries.removeIf(c -> !c.getName().contains("xx"));
This is more efficient than creating a stream and a new collection, but it alters the list.
Upvotes: 2
Reputation: 2220
Sure, what happens is that: .stream() doesn't change the actual list.
What you can do is:
List<Country> countries = CsvToBeanConverterCountry("country.csv");
countries
.stream()
.filter(s -> s.getName().contains("xx"))
.forEach(s -> System.out.println(s.getName()));
Upvotes: 1
Reputation: 18235
You ignored the result of collect:
countries.stream().filter(s -> s.getName().contains("xx"))
.collect(Collectors.toList());
So you should assign the result to a new list and print that list only
List<Country> result = countries.stream()...
result.forEach(...)
Upvotes: 7
Reputation: 45339
You should assign the result to countries
:
countries = countries.stream().filter(s -> s.getName()
.contains("xx")).collect(Collectors.toList());
countries.forEach(s -> System.out.println(s.getName()));
countries.stream().filter(...)
does not filter the countries
list inline, it runs a stream and the result is ignored.
Also, you can run forEach
on the stream directly without collecting into a list first:
countries.stream().filter(s -> s.getName()
.contains("xx"))
.forEach(s -> System.out.println(s.getName()));
Upvotes: 3