본문 바로가기
프로그래밍/JAVA

[JAVA] HashMap 에서 max 값의 key 구하기

by vivi 2021. 10. 21.

검색해보니 여러가지 방법이 있는데 그 중에서 가장 간단한 방법 기록용 -ㅅ -;;

max값이 여러개 일 때 여러 key를 list로 받는 방법도 있으므로 참고.

  Key max_key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();

 

Comparator를 활용하는 방법

Comparator<Entry<Long, Integer>> comparator = new Comparator<Entry<Long, Integer>>() {
			@Override
			public int compare(Entry<Long, Integer> e1, Entry<Long, Integer> e2) {

				if (e1.getValue() == e2.getValue())
					return e1.getKey().compareTo(e2.getKey());
				else
					return e1.getValue().compareTo(e2.getValue());
			}
		};

		Entry<Long, Integer> pe = Collections.max(plus.entrySet(), comparator);

댓글