Java 通过 lambda 表达式应用过滤器后如何获取流的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29048988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the size of a Stream after applying a filter by lambda expression?
提问by Abdennour TOUMI
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
afterapplying filter
, given that locales.size()
gives me the size beforeapplying filter
?
考虑到申请前的尺寸,我如何获得申请locales
ArrayList
后的尺寸?filter
locales.size()
filter
采纳答案by Alexis C.
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.
当您从列表中获取流时,它不会修改列表。如果你想在过滤后获得流的大小,你可以调用count()
它。
long sizeAfterFilter =
locales.stream().filter(l -> l.getLanguage().equals("en")).count();
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
.
如果您想获得一个新列表,只需调用.collect(toList())
结果流即可。如果您不担心就地修改列表,您可以简单地removeIf
在List
.
locales.removeIf(l -> !l.getLanguage().equals("en"));
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)
).
请注意,Arrays.asList
返回一个固定大小的列表,以便它会抛出一个异常,但你可以在包裹它ArrayList
,或者干脆收集过滤流的内容List
(相应地ArrayList
)使用Collectors.toList()
(相应的Collectors.toCollection(ArrayList::new)
)。
回答by Bohemian
Use the count()
method:
使用count()
方法:
long matches = locales.stream()
.filter(l -> l.getLanguage() == "en")
.count();
Note that you are comparing Strings using ==
. Prefer using .equals()
. While ==
will work when comparing interned Strings, it fails otherwise.
请注意,您正在使用==
. 更喜欢使用.equals()
. 虽然==
在比较实习字符串时会起作用,否则会失败。
FYI it can be coded using only method references:
仅供参考,它可以仅使用方法引用进行编码:
long matches = locales.stream()
.map(Locale::getLanguage)
.filter("en"::equals)
.count();