簡體   English   中英

如何使用樹集對哈希圖中的值進行排序?

[英]How to sort values in hashmap by using treeset?

我有鍵值,現在我只想通過將其添加到樹集中來對值進行排序。 因為樹集執行升序排序。

存在一種轉換方法稱為將映射轉換為列表。 但這是一種忙碌的方法,有人可以對此發表評論嗎?

package practice;
import java.io.ObjectInputStream.GetField;
import java.util.*;
import java.util.Map.Entry;

public class example1{
    public static void main(String[] args) {
        Map<Integer,String> map = new HashMap<Integer,String>();
        map.put(1, "h");
        map.put(2, "l");
        map.put(3, "a");
        System.out.println(map);
        System.out.println("unsort");
        for(Map.Entry m:map.entrySet()) {
            System.out.println(m.getKey()+" - "+m.getValue());
        }
        System.out.println("sorting by values");
    }
}

是的,你可以這樣做:

HashMap<String, String> hashmap = new HashMap<>();
hashmap.put("k1", "Zz");
hashmap.put("k2", "A");
hashmap.put("k3", "Zd");
hashmap.put("k4", "Zd");

TreeSet<String> set = new TreeSet<>(hashmap.values());

但要小心,在這個例子中,這種“排序”方式將導致一個包含 3 個元素的集合(hashmap 中的第 4 個“k4”條目將丟失)

我建議使用 java 流

List<String> collect = hashmap.values().stream().sorted().collect(Collectors.toList());

這將排序並保留所有值。

    String s1 = new String("A");
    String s2 = new String("B");
    String s3 = new String("C");
    String s4 = new String("D");
    String s5 = new String("F");

    Map<String,String> map1 = new HashMap<>();

    map1.put(s1, "AAA");
    map1.put(s2, "BBB");
    map1.put(s3, "CCC");
    map1.put(s4, "FFF");
    map1.put(s5, "DDD");

    System.out.println(map1);


    Set<Map.Entry<String, String>> set = new TreeSet<>(new SortHashValue());
    set.addAll(map1.entrySet());
    System.out.println(set);

   class SortHashValue implements Comparator<Map.Entry<String, String>>{
   public int compare(Entry<String, String> e1, Entry<String, String> e2) {
    String v1 = e1.getValue();
    String v2 = e2.getValue();
    return v1.compareTo(v2);
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM