如何根据树形图的值对其进行排序?

发布于 2024-08-06 01:47:24 字数 29 浏览 5 评论 0原文

如何使用树形图的值而不是键对树形图进行排序?

How can I sort a treemap using its values rather than the key?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

同展鸳鸯锦 2024-08-13 01:47:24

这是一个解决方案:

public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return compare;
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

请注意,地图是从最高值到最低值排序的。

Here is a solution:

public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return compare;
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

Note that the map is sorted from the highest value to the lowest.

热鲨 2024-08-13 01:47:24

您不能,因为 TreeMap 的比较器仅针对键运行,例如请参阅此 构造函数

无论如何,您可以使用多个 Collections,使用 TreeMap(或更确切地说 HashMap)通过键查找元素,并使用 SortedSet 来迭代值。

You cannot as the TreeMap's comparator is run against the keys only, e.g. see this constructor.

Anyway, you can use multiple Collections, use the TreeMap (or rather HashMap) for looking up elements by keys, and have a SortedSet to iterate on the values.

盛夏尉蓝 2024-08-13 01:47:24

Google Guava 提供了 TreeMultiMap< /a>.

您还可以使用两个集合。你想实现什么目标?您能解释一下您的用例吗?

Google Guava provides a TreeMultiMap.

You could also use two collections. What are you trying to accomplish? Can you explain your use cases?

最单纯的乌龟 2024-08-13 01:47:24

Apache Commons Collections 有一个 TreeBidiMap

此类保证地图
都将按升序排列
和升序值顺序,排序
按照自然顺序
键和值的类。

这里有一个 Java5 泛型端口

Apache Commons Collections has a TreeBidiMap:

This class guarantees that the map
will be in both ascending key order
and ascending value order, sorted
according to the natural order for the
key's and value's classes.

There's a Java5-generics port of it here.

南烟 2024-08-13 01:47:24

尝试下面的代码,它对我来说效果很好。您可以选择升序或降序进行排序。

package com.rais;

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 SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

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

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

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

        // Sorting the list based on values
        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());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

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

Try below code it works fine for me. You can choose both ascending as well as descending order for sorting.

package com.rais;

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 SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

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

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

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

        // Sorting the list based on values
        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());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}
以可爱出名 2024-08-13 01:47:24

您可以尝试在创建 TreeMap 时提供一个比较器来比较值而不是键。

    final TreeMap<Integer,String> tree = new TreeMap<Integer,String>();
    tree.put(1, "1");
    tree.put(2, "2");
    tree.put(3, "3");
    tree.put(4, "4");

    final TreeMap<Integer,String> treeSortedByValues = new TreeMap<Integer,String>(new Comparator<Integer>()
    {
        public int compare(Integer o1, Integer o2)
        {
            return tree.get(o1).compareTo(tree.get(o2));
        }
    });
    treeSortedByValues.putAll(tree);

    for ( Entry<Integer, String> e : treeSortedByValues.entrySet() )
    {
        System.out.println(e.getKey() + ": " + e.getValue());
    }

You could try giving a Comparator that compare values instead of keys when you create the TreeMap.

    final TreeMap<Integer,String> tree = new TreeMap<Integer,String>();
    tree.put(1, "1");
    tree.put(2, "2");
    tree.put(3, "3");
    tree.put(4, "4");

    final TreeMap<Integer,String> treeSortedByValues = new TreeMap<Integer,String>(new Comparator<Integer>()
    {
        public int compare(Integer o1, Integer o2)
        {
            return tree.get(o1).compareTo(tree.get(o2));
        }
    });
    treeSortedByValues.putAll(tree);

    for ( Entry<Integer, String> e : treeSortedByValues.entrySet() )
    {
        System.out.println(e.getKey() + ": " + e.getValue());
    }
别把无礼当个性 2024-08-13 01:47:24

交换值和键。

更严肃地说,请提供一些您想要实现的目标的背景。也许其他处理完成后排序就足够了。

Swap values and keys.

More seriously, please provide some context what you want to achieve. Maybe it is enough to sort after other processing is finished.

秋意浓 2024-08-13 01:47:24

试试这个。这会按升序对 TreeMap 值进行排序,假设您希望按升序对值进行排序。

static <K, V> Map<K, V> sortByValues(Map<K, V> map) {
        List<?> list = new ArrayList(map.entrySet());

        // copy Map to List to use Comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) o1).getValue()).compareTo(((Map.Entry) o2).getValue());
            }
        });

        // then copy List to LinkedHashMap as it preserves insertion order
        Map<K, V> result = new LinkedHashMap<K, V>();
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            Map.Entry<K, V> m = (Map.Entry<K, V>) itr.next();
            result.put(m.getKey(), m.getValue());
        }

        return result;
    }

Try this. This sorts TreeMap values in ascending order, assuming that is how you want the values to be sorted.

static <K, V> Map<K, V> sortByValues(Map<K, V> map) {
        List<?> list = new ArrayList(map.entrySet());

        // copy Map to List to use Comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) o1).getValue()).compareTo(((Map.Entry) o2).getValue());
            }
        });

        // then copy List to LinkedHashMap as it preserves insertion order
        Map<K, V> result = new LinkedHashMap<K, V>();
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            Map.Entry<K, V> m = (Map.Entry<K, V>) itr.next();
            result.put(m.getKey(), m.getValue());
        }

        return result;
    }
三五鸿雁 2024-08-13 01:47:24

我就是这么干的..

package Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

class MyComparator implements Comparator<Object> {

    public int compare(Object o1, Object o2) {
        return (((Integer) o2).compareTo((Integer) o1));
    }
}

class MyComparator1 implements Comparator<Object> {
    Map<Integer, String> map;

    public MyComparator1(Map<Integer, String> m) {
        this.map = m;
    }

    public int compare(Object o1, Object o2) {
        return (((String) map.get(o1)).compareTo((String) map.get(o2)));
    }
}

public class Map1 {
    public static void main(String[] args) {
        Map<Integer, String> hmap = new HashMap<Integer, String>();
        hmap.put(5, "Ashok");
        hmap.put(21, "Bhanu");
        hmap.put(7, "chaman");
        hmap.put(28, "dheeraj");
        hmap.put(761, "edison");
        hmap.put(1, "frank");
        hmap.put(-6, "gopal");
        hmap.put(78, "hari");
        System.out.println("Hash Map:" + hmap);
        Map<Integer, String> tmap = new TreeMap<>(hmap);
        System.out.println("Tree Map:" + tmap);
        MyComparator comp = new MyComparator();
        Map<Integer, String> itmap = new TreeMap<>(comp);
        itmap.putAll(hmap);
        System.out.println("Tree Map Inreverse order:" + itmap);
        Map<Integer, String> orderValuemap = new TreeMap<Integer, String>(new 
            MyComparator1(hmap));
            orderValuemap.putAll(hmap);
            orderValuemap.put(22,"hello");
        for(Entry<Integer, String> mp:orderValuemap.entrySet())
            System.out.println("Value : "+mp.getValue());
    }
}

That's I have done this..

package Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

class MyComparator implements Comparator<Object> {

    public int compare(Object o1, Object o2) {
        return (((Integer) o2).compareTo((Integer) o1));
    }
}

class MyComparator1 implements Comparator<Object> {
    Map<Integer, String> map;

    public MyComparator1(Map<Integer, String> m) {
        this.map = m;
    }

    public int compare(Object o1, Object o2) {
        return (((String) map.get(o1)).compareTo((String) map.get(o2)));
    }
}

public class Map1 {
    public static void main(String[] args) {
        Map<Integer, String> hmap = new HashMap<Integer, String>();
        hmap.put(5, "Ashok");
        hmap.put(21, "Bhanu");
        hmap.put(7, "chaman");
        hmap.put(28, "dheeraj");
        hmap.put(761, "edison");
        hmap.put(1, "frank");
        hmap.put(-6, "gopal");
        hmap.put(78, "hari");
        System.out.println("Hash Map:" + hmap);
        Map<Integer, String> tmap = new TreeMap<>(hmap);
        System.out.println("Tree Map:" + tmap);
        MyComparator comp = new MyComparator();
        Map<Integer, String> itmap = new TreeMap<>(comp);
        itmap.putAll(hmap);
        System.out.println("Tree Map Inreverse order:" + itmap);
        Map<Integer, String> orderValuemap = new TreeMap<Integer, String>(new 
            MyComparator1(hmap));
            orderValuemap.putAll(hmap);
            orderValuemap.put(22,"hello");
        for(Entry<Integer, String> mp:orderValuemap.entrySet())
            System.out.println("Value : "+mp.getValue());
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文