Based on the typo, and your clarification that you are using hashmap, the order of the keys retrieval will not be consistent with the insert order. Use LinkedHashMap for that. This is using you do external sorting and then insert sorted entries into the map.
If you want the entries to be sorted while they are being inserted into the Map, use TreeMap. You can either use a custom comparator or make your key object implement Comparable interface.
-------------------
HashMap uses key.hashValue() to sort the values. Use TreeMap instead.
-------------------
I have a sorted hashmap based on values. I have sorted a hashmap based on values
No you haven't. A HashMap isn't sorted at all. You can get the values(), as a Collection, and you can sort that any way you like, but it doesn't sort the HashMap itself.
But this method didnt work. It stores the keys in random fashion.
It isn't defined to do anything differently, especially as you haven't sorted the HashMap at all.
여기서 말하는 내용을 명확히해야합니다. 값을 정렬하려면 위를 수행하십시오. 키를 정렬하려면 '
keys()
대신 위의 작업을 수행하십시오
values()
. 맵 자체를 키로 정렬하려면 TreeMap을 사용하십시오. 값에 따라지도 자체를 정렬하려는 경우 운이 좋지 않습니다.-------------------
이 시도:
public static void main(String[] args) {
Map<String, String> hm = new TreeMap<String, String>();
hm.put("AAA", "typeAAA");
hm.put("BBB", "typeBBB");
hm.put("ABB", "TypeABB");
String[] keys = hm.keySet().toArray(new String[0]);
for (String key : keys) {
System.out.println("key: " + key);
}
}
출력은 다음과 같습니다.
key: AAA
key: ABB
key: BBB
-------------------
a의 키 순서가
HashMap
정렬 된 키 목록과 동일 하기를 원하는 것 같습니다 . 이것은
단순히 불가능합니다
.
HashMap
의 키는 해시 테이블 알고리즘에 의해 결정된다; 예를 들어 키의 해시 값과 삽입 및 삭제 시퀀스에 의존하는 복잡한 프로세스.가장 가까운 방법은를 만들고 정렬 된 키 순서대로
LinkedHashMap
이전 항목을 삽입하여 채우는 것
HashMap
입니다. 그런 다음
LinkedHashMap
의 키 를 반복 하면 삽입 된 순서대로 다시 가져옵니다. 그러나 이것은 무거운 솔루션이며 나중에 "정렬 된"맵에 더 많은 항목을 추가해야하는 경우 문제가 발생합니다. 그냥 사용하는 것이 더 나을 수 있습니다
TreeMap
.
해시 맵을 변경하고 싶지 않습니다. 정렬 된 값의 순서로 키가있는 배열을 얻고 싶습니다.
이 경우 HashMap의 키를 배열로 추출하고 정렬하기 만하면됩니다. 코드는 다른 답변에 제공되었습니다.반면에, 당신이 뭔가를하고 싶은 경우에지도의 키는 항상 당신이 (당신이 다른 의견 말하는 것 같다)에 정렬 된 순서로 나올 수 있도록
하는
맵을 변경.
출처
https://stackoverflow.com/questions/7415153