ArrayList<Integer> myArrayList = new ArrayList<>;
for (int i = 0; i < 5; i++) {myArrayList.add(i);}
myArrayList.add(2);
myArrayList.add(2);
myArrayList.add(3);
//arryalist 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; } }
}
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 ie. 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 individual value is present in 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 ?