Consider the following code:
List<Locale> locales = Arrays.asList(
new Locale("en", "US"),
new Locale("ar"),
new Locale("en", "GB")
);
locales.stream().filter(l -> l.getLanguage() == "en");
How do I get the size of the locales
ArrayList
after applying filter
, given that locales.size()
gives me the size before applying filter
?
When you get a stream from the list, it doesn't modify the list. If you want to get the size of the stream after the filtering, you call
count()
on it.If you want to get a new list, just call
.collect(toList())
on the resulting stream. If you are not worried about modifying the list in place, you can simply useremoveIf
on theList
.Note that
Arrays.asList
returns a fixed-size list so it'll throw an exception but you can wrap it in anArrayList
, or simply collect the content of the filtered stream in aList
(resp.ArrayList
) usingCollectors.toList()
(resp.Collectors.toCollection(ArrayList::new)
).Use the
count()
method:Note that you are comparing Strings using
==
. Prefer using.equals()
. While==
will work when comparing interned Strings, it fails otherwise.FYI it can be coded using only method references: