ArrayList<Integer> myArrayList = new ArrayList<>;
for (int i = 0; i < 5; i++) {
myArrayList.add(i);
}
myArrayList.add(2);
myArrayList.add(2);
myArrayList.add(3);
//arryaylist contains: (0,1,2,3,4,2,2,3)
我想向一个方法提供输入,并让它返回输入在数组中出现的次数。例如:
public int someMethod(int searchVal) {
//code
//returns int
}
System.out.println(someMethod(2));
//prints 3
我可以想到这样的方法:
public int someMethod(int searchVal) {
int counter = 0;
for (int i : myArraylist) {
if (i == searchVal) {
counter +=1;
}
}
return counter;
}
但是我需要此方法的数组列表非常长,我将对 ArrayList 中的每个可能值多次使用它。含义即 someMethod(0)、someMethod(1)、someMethod(2)、someMethod(3)、someMethod(4)。
在示例中我有 int,但我将使用 ArrayList。形式为: ArrayList
共有三个选项
import java.util.ArrayList;
import java.util.Collections;
public class FrequencyExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
list.add("apple");
String valueToCount = "apple";
int frequency = Collections.frequency(list, valueToCount);
System.out.println("The value '" + valueToCount + "' appears " + frequency + " times.");
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class FrequencyExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
list.add("apple");
// Create a map to store the frequency of each element
Map<String, Integer> frequencyMap = new HashMap<>();
// Populate the frequency map
for (String item : list) {
frequencyMap.put(item, frequencyMap.getOrDefault(item, 0) + 1);
}
String valueToCount = "apple";
int frequency = frequencyMap.getOrDefault(valueToCount, 0);
System.out.println("The value '" + valueToCount + "' appears " + frequency + " times.");
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class FrequencyExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
list.add("apple");
String valueToCount = "apple";
long frequency = list.stream()
.filter(item -> item.equals(valueToCount))
.count();
System.out.println("The value '" + valueToCount + "' appears " + frequency + " times.");
}
}