I made an int[] array that will be fill by score from users input. My task is to create a frequency table, which count how many times did a certain score entered by the user. Example: user entered the following score, 13,13,13,16,16,19,22. Then, in a tabular form 13 - 3 ,16 - 2, 19 - 1, 22 - 1. Sorry bad english
You can do something like:
Map<Integer, Integer> numberCountMap = ....
for (int i=0; i<numbers.length; i++) {
numberCountMap.compute(numbers[i], (key, value) -> value == null ? 1 : value + 1);
}
//print map or sort by value if you need most frequent one to be on top
This will do the job
import java.util.HashSet;
import java.util.Set;
public class NumbersInArray {
public static void main(String[] args) {
int [] arr = {1,2,1,1,5,5,5,3,4,5,6};
Set<Integer> set = new HashSet();
//adding numbers to set will remove duplicates
for(int i =0 ; i<arr.length;i++) {
set.add(arr[i]);
}
int counter = 0;
int[] arrayToCheck = set.stream().mapToInt(Number::intValue).toArray();
for(int i = 0; i<set.size(); i++) {
counter = 0;
for(int j =0; j<arr.length;j++) {
if(arrayToCheck[i]== arr[j]) {
counter++;
}
}
System.out.println(arrayToCheck[i] + "-" + counter);
}
}
}
In Java 8 you can do this
Map<Integer, Long> freq = Arrays.stream(array).boxed().
collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.