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)
I want to give input to a method, and for it to return amount of times the input is seen in the array. For example:
public int someMethod(int searchVal) {
//code
//returns int
}
System.out.println(someMethod(2));
//prints 3
I can think of a way like:
public int someMethod(int searchVal) {
int counter = 0;
for (int i : myArraylist) {
if (i == searchVal) {
counter +=1;
}
}
return counter;
}
But the arraylist I need this method for is very long and I’m going to use it multiple times for each of the possible values in the ArrayList. Meaning i.e. someMethod(0), someMethod(1), someMethod(2), someMethod(3), someMethod(4).
In the example I have int, but I will use ArrayList. In form of: ArrayList<ArrayList< Integer >> myArrayList = ((1,2) , (2,1), (1,2), (3,0)…) So .sort() will not work.
- Is there a faster way to generally calculate how many times an individual value is present in an ArrayList?
- Since I’m going to use this on all values, is there a faster way of doing this than having method that compares each value?
7
To count the occurrences of all list values, you can use a stream with Collectors.groupingBy
and Collectors.counting
myArrayList.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
This groups the values of the list by their identity, and then for each group, counts how many elements are in the group, returning a map with the list values as the keys, and the occurrence counts as the values.
In your example:
var myArrayList = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
myArrayList.add(i);
}
myArrayList.add(2);
myArrayList.add(2);
myArrayList.add(3);
Map<Integer, Long> counts =
myArrayList.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counts);
Output:
{0=1, 1=1, 2=3, 3=2, 4=1}