Вот один из способов сделать это.
int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
};
Arrays.sort(array);
int count = 1;
int v = array[0];
for (int i = 1;i < array.length;) {
while (i < array.length && v == array[i++]) {
count++;
}
if (count > 1) {
System.out.println(v + " occurs " + count + " times.");
}
v = array[i - 1];
count = 1;
}
Вот несколько дополнительных способов, которые не требуют сортировки.
public static void method2() {
int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
};
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
// If the map contains the number, bump the count
if (map.containsKey(i)) {
int count = map.get(i)+1; // increment count
map.put(i,count); // put it back
} else {
map.put(i, 1); // intialize count to 1
}
}
// Now go thru the map and display only the numbers when the value is > 1
for (Map.Entry<?,Integer> e : map.entrySet()) {
if (e.getValue() > 1) {
System.out.println(e.getKey() + " occurs " + e.getValue() + "
times.");
}
}
}
Следующий метод использует возможности Stream, начиная с Java 8.
public static void method3() {
int[] array = { 2, 0, -12, 0, 23, 45, -4, -5, 2, 23, 0, 9, -7
};
Arrays.stream(array)
// Convert the integers to an Integer object.
.boxed()
// group the values into a Map<Integer, Integer> where the key is
// the number
// and the value is the count.
.collect(Collectors.groupingBy(k -> k, Collectors.counting()))
// grab the entry set of that map
.entrySet()
// convert it to a stream
.stream()
// filter for entrysets where the value > 1
.filter(e -> e.getValue() > 1)
// and forEach entry set that passes the filter, print out the
// number and its count.
.forEach(e -> System.out.println(
e.getKey() + " occurs " + e.getValue() + " times."));
}