[英]Java - write string to file line by line vs one-liner / cannot convert String to String[]
[英]One-liner to count number of occurrences of String in a String[] in Java?
我有一個String
數組:
String[] myArray = {"A", "B", "B", "C"};
有沒有快速計算該數組中字符串出現次數的方法? 是的,我知道我可以迭代並自己做計數:
int count = 0;
String whatToFind = "B";
for (String s : myArray) {
if (s.equals(whatToFind)) {
++count;
}
}
但我想知道是否有一個實用功能。 我在Arrays
或ArrayUtils
找不到任何東西。 是否可以使用單線程進行此操作?
您可以使用frequency
方法 :
List<String> list = Arrays.asList(myArray);
int count = Collections.frequency(list, "B");
或者在一行中:
int count = Collections.frequency(Arrays.asList(myArray), "B");
使用Java 8,您還可以編寫:
long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();
或者使用方法參考:
long count = Arrays.stream(myArray).filter("B"::equals).count();
您也可以嘗試使用充滿有用實用程序的Guava 。 使用以下代碼,您可以通過Multiset計算頻率:
public static void main(final String[] args) {
String[] myArray = {"A", "B", "B", "C"};
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(new ArrayList<String>(Arrays.asList(myArray)));
int counts=wordsMultiset.count("B");
System.out.println(counts);
}
雖然我知道你正在尋找一個單一的襯墊,但是Guava充滿了更多的工具,而常規的java utils是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.