通过lambda表达式应用过滤器后,如何获取Stream的大小? [英] How to get the size of a Stream after applying a filter by lambda expression?

查看:763
本文介绍了通过lambda表达式应用过滤器后,如何获取Stream的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆