如何在Java中对HashMap进行排序

112 java sorting hashmap

我们如何排序HashMap<key, ArrayList>

我想根据一个值来排序ArrayList.

pgr*_*ras 130

你必须使用HashMap吗?如果只需要Map Interface,请使用TreeMap


如果要通过比较HashMap中的值进行排序.如果要在对HashMap的值进行排序后执行此操作,则必须编写代码才能执行此操作:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "\t" + p.getAge());
}
Run Code Online (Sandbox Code Playgroud)

如果你想经常访问这个排序列表,那么你可以将你的元素插入到a中HashMap<TreeSet<Person>>,尽管集合和列表的语义有点不同.

  • 还有几点:首先,您需要做出两个决定:(1)您是想按值还是按键排序,(2)您是否可以在开始时控制集合,这样您就可以使用内置排序,与您交付现有地图时只需要按某种顺序迭代它们.此外,LinkedHashMap可以通过插入顺序(我经常喜欢调试)或访问顺序来维护.最后,如果您正在做很多这样的事情,您可以查看Java 1.6和[NavigableMap](http://java.sun.com/javase/6/docs/api/java/util/NavigableMap.html),真棒东西! (2认同)
  • 如果要按键排序,请使用SortedMap.它为您提供自动排序键. (2认同)

gok*_*ari 36

按照hasmap键排序列表:

SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
Run Code Online (Sandbox Code Playgroud)

按散列映射值排序列表:

SortedSet<String> values = new TreeSet<String>(myHashMap.values());
Run Code Online (Sandbox Code Playgroud)

如果是重复的地图值:

List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
Run Code Online (Sandbox Code Playgroud)

祝好运!


小智 23

http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/

得到钥匙

List keys = new ArrayList(yourMap.keySet());
Run Code Online (Sandbox Code Playgroud)

排序他们

 Collections.sort(keys)
Run Code Online (Sandbox Code Playgroud)

打印它们.

在任何情况下,您都不能在HashMap中排序值(根据API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time).

虽然您可以将所有这些值推送到LinkedHashMap以后使用.


JH.*_*JH. 13

好像你可能想要一个树形图.

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

如果适用,您可以将自定义比较器传递给它.


Vit*_*nko 10

在Java 8中:

Comparator<Entry<String, Item>> valueComparator = 
    (e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());

Map<String, Item> sortedMap = 
    unsortedMap.entrySet().stream().
    sorted(valueComparator).
    collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                             (e1, e2) -> e1, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

使用番石榴:

Map<String, Item> map = ...;
Function<Item, Integer> getField = new Function<Item, Integer>() {
    public Integer apply(Item item) {
        return item.getField(); // the field to sort on
    }
};
comparatorFunction = Functions.compose(getField, Functions.forMap(map));
comparator = Ordering.natural().onResultOf(comparatorFunction);
Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator);
Run Code Online (Sandbox Code Playgroud)


Mus*_*ven 9

自定义比较功能,包括土耳其语字母其他语言的功能,而不是英语.

public <K extends Comparable,V extends Comparable> LinkedHashMap<K,V> sortByKeys(LinkedHashMap<K,V> map){
    List<K> keys = new LinkedList<K>(map.keySet());
    Collections.sort(keys, (Comparator<? super K>) new Comparator<String>() {
        @Override
        public int compare(String first, String second) {
            Collator collator = Collator.getInstance(Locale.getDefault());
            //Collator collator = Collator.getInstance(new Locale("tr", "TR"));
            return collator.compare(first, second);
        }
    });

    LinkedHashMap<K,V> sortedMap = new LinkedHashMap<K,V>();
    for(K key: keys){
        sortedMap.put(key, map.get(key));
    }

    return sortedMap;
}
Run Code Online (Sandbox Code Playgroud)

这是使用示例如下

LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>();
ligList = sortByKeys(ligList);
Run Code Online (Sandbox Code Playgroud)


Sma*_*ery 4

如果没有更多信息,很难确切地知道您想要什么。但是,在选择使用哪种数据结构时,您需要考虑它的用途。哈希图不是为排序而设计的 - 它们是为轻松检索而设计的。因此,在您的情况下,您可能必须从哈希图中提取每个元素,并将它们放入更有利于排序的数据结构中,例如堆或集合,然后在那里对它们进行排序。