Java求数组中出现次数最多的元素
package com.ycy1;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Test06 {
public static void main(String[] args) {
byte[] b = { 1, 3, 5, 8, 5, 7, 5, 7, 5 };
Test06.findNum1(b);
Test06.findNum2(b);
}
public static void findNum1(byte[] b) {
int[] array = new int[b.length];
for (int i = 0; i < b.length; i++) {
int temp = 1;
for (int j = i + 1; j < b.length; j++) {
if (b[i] == b[j]) {
temp++;
}
}
array[i] = temp;
}
int maxIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > array[maxIndex]) {
maxIndex = i;
}
}
System.out.println("出现次数最多的元素是:" + b[maxIndex]);
}
public static void findNum2(byte[] b) {
HashMap<Byte, Integer> hashMap = new HashMap<>();
for (int i = 0; i < b.length; i++) {
if(hashMap.containsKey(b[i])) {
hashMap.put(b[i], hashMap.get(b[i]) +1);
}else {
hashMap.put(b[i], 1);
}
}
Collection<Integer> values = hashMap.values();
Integer max = Collections.max(values);
byte maxByte = 0;
Set<Entry<Byte,Integer>> entrySet = hashMap.entrySet();
Iterator<Entry<Byte, Integer>> iterator = entrySet.iterator();
while(iterator.hasNext()) {
Entry<Byte, Integer> next = iterator.next();
Integer value = next.getValue();
if(max == value) {
maxByte = next.getKey();
break;
}
}
System.out.println("出现次数最多的元素是:" + maxByte);
}
}