单行计算在Java中的String []字符串中出现的次数? [英] One-liner to count number of occurrences of String in a String[] in Java?

查看:277
本文介绍了单行计算在Java中的String []字符串中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串的数组:

String[] myArray = {"A", "B", "B", "C"};

是否有一个快速的方法来计算该阵列中字符串出现的次数?是的,我知道我可以遍历和执行COUNT自己:

Is there a quick way to count the number of occurrences of a string in that array? Yes, I know I can iterate and do the count myself:

int count = 0;
String whatToFind = "B";
for (String s : myArray) {
    if (s.equals(whatToFind)) {
        ++count;
    }
}

但我想知道是否有这个效用函数。我无法找到阵列 ArrayUtils 东西。是否有可能有一个班轮做到这一点?

But I was wondering if there was a utility function for this. I couldn't find anything in Arrays or ArrayUtils. Is it possible to do this with a one-liner?

推荐答案

您可以使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#frequency%28java.util.Collection,%20java.lang.Object%29\"相对=nofollow>在频率方法:

You can use the frequency method:

List<String> list = Arrays.asList(myArray);
int count = Collections.frequency(list, "B");

或在一行:

int count = Collections.frequency(Arrays.asList(myArray), "B");


在Java 8还可以这样写:


With Java 8 you can also write:

long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();

或用一个方法参照:

long count = Arrays.stream(myArray).filter("B"::equals).count();

这篇关于单行计算在Java中的String []字符串中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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