简体   繁体   English

计算ArrayList上的特定单词<String>

[英]Count Specific word on ArrayList<String>

Imagine that you have this situation: 想象一下您有这种情况:

List<String> al = new ArrayList<>();
    al.add("[I] am");
    al.add("you are");
    al.add("I");
    al.add("[I] like java");

Now I want to count the sequence [I] (in this case it will count 2 times). 现在,我想对序列[I]进行计数(在这种情况下,它将计数2次)。 The Link How to count the number of occurrences of an element in a List just pust one word, but on my example I have more than one, ie, Collections.frequency(al, "[I]") do not work. 如何计算列表中元素出现次数的链接只是一个单词,但是在我的示例中,我有多个单词,即Collections.frequency(al,“ [I]”)不起作用。

How can I achieve this preferentially using Java 8 ? 如何使用Java 8优先实现此目的?

Another way is to split the stream by space and then check whether chunk is equal to [I] eg 另一种方法是按空间划分流,然后检查块是否等于[I]例如

System.out.println(al.stream().map((w) -> w.split(" ")).flatMap(Arrays::stream).filter((i) ->i.equals("[I]")).count());

Using equals have advantage over contains because let say your list contains words like below 使用equals具有优于contains的优势,因为可以说您的列表包含如下单词

List<String> al = new ArrayList<>();
        al.add("[I] am [I]");
        al.add("you are");
        al.add("I");
        al.add("[I] like java");

This solution will return 3 as expected but the solution mentioned by Bohuslav Burghardt will return 2 该解决方案将按预期返回3,但Bohuslav Burghardt提到的解决方案将返回2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM