당신은 삽입 순서를 보장하는하는 TreeSet
을 구축 할 수 있습니다 :
@Test
public void treeMapSortedByValue() {
// given the following map:
TreeMap<Integer, Double> map = new TreeMap<Integer, Double>();
map.put(2, Math.E);
map.put(1, Math.PI);
map.put(3, 42.0);
// build a TreeSet of entries
Set<Map.Entry<Integer, Double>> sortedEntries = new TreeSet<Map.Entry<Integer, Double>>(new DoubleComparator());
sortedEntries.addAll(map.entrySet());
// optionally you can build a List<Double> with the sorted
List<Double> doubles = new LinkedList<Double>();
for (Map.Entry<Integer, Double> entry : sortedEntries) {
doubles.add(entry.getValue());
}
}
이 당신을 제공해야합니다 : [2.718281828459045, 3.141592653589793, 42.0]
(NB : [Math.E, Math.PI, Math.UNIVERSAL_ANSWER]
:-)를.
PS
Comparator
:
class DoubleComparator implements Comparator<Map.Entry<Integer, Double>> {
@Override
public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) {
return Double.compare(o1.getValue(), o2.getValue());
}
}
출처
2010-01-27 10:28:01
dfa
내가 정수가 무엇을 나타내는 지 물어 봐도 될까요? TreeMap 대신 다른 데이터 구조를 제안하는 데 도움이된다면 ... – pgras
제목을 명확히 할 수 있습니까? 당신이 어떤 필드를 정렬하려고하는지 명확하지 않습니다. – cmcginty