1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class LottoEntryComparator implements Comparator<Entry<Integer, Integer>> {
@Override public int compare(Entry<Integer, Integer> arg0, Entry<Integer, Integer> arg1) { int result = arg0.getValue().compareTo(arg1.getValue()) * -1; if(result == 0){ result = arg0.getKey().compareTo(arg1.getKey()) * -1; } return result; } }
public class MapLottoTest {
public static void main(String[] args) { Map<Integer, Integer> lottoMap = new HashMap<>(); Random rd = new Random(); for(int i=0; i<100000; i++){ int num = rd.nextInt(45)+1; if(lottoMap.containsKey(num)){ lottoMap.put(num, lottoMap.get(num)+1); }else{ lottoMap.put(num, 1); } } sortLottoByV(lottoMap); } public static void sortLottoByV(Map<Integer, Integer> map){ TreeSet<Map.Entry<Integer, Integer>> sortedEntries = new TreeSet<>(new LottoEntryComparator()); sortedEntries.addAll(map.entrySet()); String pattern = "{0}번호: {1}\t(총 누적:{2})"; for (int i=0; i<7; i++){ Entry<Integer, Integer> first = sortedEntries.pollFirst(); String msg = null; if(i == 6){ msg = MessageFormat.format(pattern, "보너스", first.getKey(), first.getValue()); }else{ msg = MessageFormat.format(pattern, "당첨", first.getKey(), first.getValue()); } System.out.println(msg); } }
}
당첨번호: 38 (총 누적:2,336) 당첨번호: 1 (총 누적:2,328) 당첨번호: 5 (총 누적:2,321) 당첨번호: 28 (총 누적:2,316) 당첨번호: 29 (총 누적:2,292) 당첨번호: 27 (총 누적:2,283) 보너스번호: 45 (총 누적:2,268)
|