通过lambda表达式应用过滤器后,如何获取Stream的大小? [英] How to get the size of a Stream after applying a filter by lambda expression?
问题描述
考虑以下代码:
List<Locale> locales = Arrays.asList(
new Locale("en", "US"),
new Locale("ar"),
new Locale("en", "GB")
);
locales.stream().filter(l -> l.getLanguage() == "en");
在应用filter
之后,如何获得locales
ArrayList
的大小,考虑到locales.size()
在应用
How do I get the size of the locales
ArrayList
after applying filter
, given that locales.size()
gives me the size before applying filter
?
推荐答案
从列表中获取流时,它不会修改列表.如果要在过滤后获取流的大小,请在其上调用count()
.
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.
long sizeAfterFilter =
locales.stream().filter(l -> l.getLanguage().equals("en")).count();
如果要获取新列表,只需在结果流上调用.collect(toList())
.如果您不担心就地修改列表,只需在List
上使用removeIf
.
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 use removeIf
on the List
.
locales.removeIf(l -> !l.getLanguage().equals("en"));
请注意,Arrays.asList
返回一个固定大小的列表,因此它将引发异常,但是您可以将其包装在ArrayList
中,或者只是将过滤后的流的内容收集在List
中(分别是ArrayList
)使用Collectors.toList()
(resp.Collectors.toCollection(ArrayList::new)
).
Note that Arrays.asList
returns a fixed-size list so it'll throw an exception but you can wrap it in an ArrayList
, or simply collect the content of the filtered stream in a List
(resp. ArrayList
) using Collectors.toList()
(resp. Collectors.toCollection(ArrayList::new)
).
这篇关于通过lambda表达式应用过滤器后,如何获取Stream的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!