Вы можете использовать Collections::frequency
для подсчета вхождений, например,
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
Set<Integer> set = new HashSet<Integer>(list);
for (int n : set) {
System.out.println("Frequency of " + n + " is " + Collections.frequency(list, n));
}
}
}
Вывод:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1
Другой пример подсчета дубликатов: :
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
boolean duplicatesFound = false;
for (int n : nums) {
if (map.get(n) == null) {
map.put(n, 1);
} else {
map.put(n, map.get(n) + 1);
duplicatesFound = true;
}
}
if (duplicatesFound) {
System.out.println("Duplicates are as follows:");
map.entrySet().stream().filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + " has occurred " + e.getValue() + " times."));
} else {
System.out.println("There are no duplicates in the list");
}
[Обновление]
Еще одно решение (спасибо, @Andreas за предложение):
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Long> frequencyMap = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(n -> n, Collectors.counting()));
frequencyMap.forEach((n, count) -> {
System.out.println("Frequency of " + n + " is " + count);
});
}
}
Выход:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1