计算ArrayList中给定字符串的出现次数,可以使用以下方法:
以下是示例代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayListStringCount {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "apple", "orange", "banana"));
String target = "banana";
int count = countOccurrences(list, target);
System.out.println("The target string \"" + target + "\" appears " + count + " times in the ArrayList.");
}
public static int countOccurrences(List<String> list, String target) {
int count = 0;
for (String s : list) {
if (s.equals(target)) {
count++;
}
}
return count;
}
}
输出结果:
The target string "banana" appears 2 times in the ArrayList.
使用Java 8的Stream API实现:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayListStringCount {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "apple", "orange", "banana"));
String target = "banana";
int count = countOccurrences(list, target);
System.out.println("The target string \"" + target + "\" appears " + count + " times in the ArrayList.");
}
public static int countOccurrences(List<String> list, String target) {
return (int) list.stream().filter(target::equals).count();
}
}
输出结果与上述示例相同。
领取专属 10元无门槛券
手把手带您无忧上云