123

我们如何对 a 进行排序HashMap<key, ArrayList>

我想根据ArrayList.

4

17 回答 17

146

你必须使用HashMap吗?如果您只需要地图接口,请使用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());
}

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

于 2009-04-23T06:57:35.197 回答
39

按 hasmap 键排序的列表:

SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());

按哈希图值排序的列表:

SortedSet<String> values = new TreeSet<String>(myHashMap.values());

如果地图值重复:

List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);

祝你好运!

于 2013-02-18T12:59:45.600 回答
23

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

拿到钥匙

List keys = new ArrayList(yourMap.keySet());

对它们进行排序

 Collections.sort(keys)

打印它们。

在任何情况下,您都不能在 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, 以供以后使用。

于 2009-04-23T09:23:52.333 回答
13

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

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

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

于 2009-04-23T06:58:25.723 回答
11

在 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));

使用番石榴

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);
于 2013-03-16T23:10:48.667 回答
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;
}

这是使用示例,如下所示

LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>();
ligList = sortByKeys(ligList);
于 2013-05-25T00:52:37.383 回答
4

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

于 2009-04-23T06:53:05.283 回答
3

如果您想将 Map 与 SortedMap 结合起来进行高效检索,您可以使用ConcurrentSkipListMap

当然,您需要将键作为用于排序的值。

于 2009-04-23T07:19:09.153 回答
3

您是否考虑过使用 LinkedHashMap<>()..?

  public static void main(String[] args) {
    Map<Object, Object> handler = new LinkedHashMap<Object, Object>();
    handler.put("item", "Value");
    handler.put(2, "Movies");
    handler.put("isAlive", true);

    for (Map.Entry<Object, Object> entrY : handler.entrySet())
        System.out.println(entrY.getKey() + ">>" + entrY.getValue());

    List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>();
    Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> a,
                Map.Entry<String, Integer> b) {
            return a.getValue().compareTo(b.getValue());
        }
    });
}

结果变成一个有组织的链接对象。

 item>>Value
 2>>Movies
 isAlive>>true

检查从这里挑选的分拣部分..

于 2015-03-04T14:13:29.510 回答
3

我开发了一个类,可用于根据键和值对地图进行排序。基本思想是,如果您使用键对地图进行排序,然后从您的地图创建一个 TreepMap,它将按键对地图进行排序。如果按值排序,则从 entrySet 创建一个列表,并使用比较器接口对列表进行排序。

这是完整的解决方案:

public static void main(String[] args) {
    Map<String, Integer> unSortedMap = new LinkedHashMap<String, Integer>();
    unSortedMap.put("A", 2);
    unSortedMap.put("V", 1);
    unSortedMap.put("G", 5);
    System.out.println("Unsorted Map :\n");
    for (Map.Entry<String, Integer> entry : unSortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Keys :\n");
    Map<String, Integer> keySortedMap = new TreeMap<String, Integer>(unSortedMap);
    for (Map.Entry<String, Integer> entry : keySortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Values :\n");
    List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(unSortedMap.entrySet());
    Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {

        @Override
        public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
            return obj1.getValue().compareTo(obj2.getValue());
        }
    });
    unSortedMap.clear();
    for (Entry<String, Integer> entry : entryList) {
        unSortedMap.put(entry.getKey(), entry.getValue());
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
}

代码经过适当测试:D

于 2016-02-16T13:15:20.167 回答
2

一个正确的答案。

HashMap<Integer, Object> map = new HashMap<Integer, Object>();

ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
  @Override
  public int compare(Integer a, Integer b) {
    return a.compareTo(b);
  }
});

for (Integer key: sortedKeys) {
  //map.get(key);
}

请注意,正如其他答案所指出的那样,HashMap 本身无法维护排序。这是一个哈希映射,哈希值是未排序的。因此,您可以在需要时对键进行排序,然后按顺序访问值,如上所示,或者您可以找到一个不同的集合来存储您的数据,例如 Pairs/Tuples 的 ArrayList,例如在阿帕奇共享:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

于 2018-07-31T14:51:16.540 回答
2

按值对 HashMap 进行排序:

正如其他人指出的那样。HashMaps 便于查找,如果您更改它或尝试在地图本身内部进行排序,您将不再有 O(1) 查找。

您的排序代码如下:

class Obj implements Comparable<Obj>{
    String key;
    ArrayList<Integer> val;
    Obj(String key, ArrayList<Integer> val)
    {
    this.key=key;
    this.val=val;
    }
    public int compareTo(Obj o)
    {
     /* Write your sorting logic here. 
     this.val compared to o.val*/
     return 0;
    }
}

public void sortByValue(Map<String, ArrayList<>> mp){

    ArrayList<Obj> arr=new ArrayList<Obj>();
    for(String z:mp.keySet())//Make an object and store your map into the arrayList
    {

        Obj o=new Obj(z,mp.get(z));
        arr.add(o);
    }
    System.out.println(arr);//Unsorted
    Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
    System.out.println(arr);//Sorted
}
于 2015-07-21T17:52:34.330 回答
2

按键排序:

public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();

    map.put("b", "dd");
    map.put("c", "cc");
    map.put("a", "aa");

    map = new TreeMap<>(map);

    for (String key : map.keySet()) {
        System.out.println(key+"="+map.get(key));
    }
}
于 2018-08-29T11:11:10.367 回答
0

我开发了一个经过全面测试的工作解决方案。希望能帮助到你

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;


public class Main {
    public static void main(String[] args) {
    try {
        BufferedReader in = new BufferedReader(new java.io.InputStreamReader           (System.in));
            String str;

        HashMap<Integer, Business> hm = new HashMap<Integer, Business>();
        Main m = new Main();


        while ((str = in.readLine()) != null) {


            StringTokenizer st = new StringTokenizer(str);
            int id = Integer.parseInt(st.nextToken());    // first integer
            int rating = Integer.parseInt(st.nextToken());    // second 

            Business a = m.new Business(id, rating);


            hm.put(id, a);


            List<Business> ranking = new ArrayList<Business>(hm.values());

            Collections.sort(ranking, new Comparator<Business>() {

                public int compare(Business i1, Business i2) {
                    return i2.getRating() - i1.getRating();
                }
            });

            for (int k=0;k<ranking.size();k++) {
                System.out.println((ranking.get(k).getId() + " " + (ranking.get(k)).getRating()));
            }


        }
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


}
public class Business{

    Integer id;
    Integer rating;

    public Business(int id2, int rating2)
    {
        id=id2;
        rating=rating2;

    }

    public Integer getId()
    {
        return id;
    }
    public Integer getRating()
    {
        return rating;
    }


}
}
于 2015-04-03T15:38:16.447 回答
0

HashMap 不维护任何顺序,因此如果您想要任何排序,则需要将其存储在其他东西中,这是一个映射并且可以具有某种排序,例如 LinkedHashMap

下面是一个简单的程序,您可以通过它按键、值、升序、降序排序..(如果您修改压缩器,您可以对键和值使用任何类型的排序)

package com.edge.collection.map;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByKeyValue {
Map<String, Integer> map = new HashMap<String, Integer>();

public static void main(String[] args) {

    SortMapByKeyValue smkv = new SortMapByKeyValue();
    smkv.createMap();

    System.out.println("After sorting by key ascending order......");
    smkv.sortByKey(true);

    System.out.println("After sorting by key descindeng order......");
    smkv.sortByKey(false);

    System.out.println("After sorting by value ascending order......");
    smkv.sortByValue(true);

    System.out.println("After sorting by value  descindeng order......");
    smkv.sortByValue(false);

}

void createMap() {
    map.put("B", 55);
    map.put("A", 80);
    map.put("D", 20);
    map.put("C", 70);
    map.put("AC", 70);
    map.put("BC", 70);
    System.out.println("Before sorting......");
    printMap(map);
}

void sortByValue(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getValue().compareTo(o2.getValue());
            } else {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);

}

void sortByKey(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getKey().compareTo(o2.getKey());
            } else {
                return o2.getKey().compareTo(o1.getKey());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);
}

public void printMap(Map<String, Integer> map) {
    // System.out.println(map);
    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }
}
}

这是git链接

于 2018-02-06T15:54:04.013 回答
0

使用 pair 类将 hashmap 转换为 ArrayList

Hashmap<Object,Object> items = new HashMap<>();

List<Pair<Object,Object>> items = new ArrayList<>();

因此您可以根据需要对其进行排序,或者通过添加顺序进行排序。

于 2018-03-12T10:04:08.943 回答
0

在 Java 中按值对 HashMap 进行排序:

public class HashMapSortByValue {
    public static void main(String[] args) {

        HashMap<Long,String> unsortMap = new HashMap<Long,String>();
            unsortMap.put(5l,"B");
            unsortMap.put(8l,"A");
            unsortMap.put(2l, "D");
            unsortMap.put(7l,"C" );

            System.out.println("Before sorting......");
            System.out.println(unsortMap);

            HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
            System.out.println("After sorting......");
            System.out.println(sortedMapAsc);

    }

    public static HashMap<Long,String> sortByComparator(
            HashMap<Long,String> unsortMap) {

            List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
                unsortMap.entrySet());

            Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
                public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });

            HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
            for (Entry<Long,String> entry : list) {
              sortedMap.put(entry.getKey(), entry.getValue());
            }
            return sortedMap;
          }

}
于 2018-08-27T12:53:20.373 回答