用Java排序元素

问题描述 投票:0回答:2

我正在尝试通过降低频率对给定元素的列表进行排序。如果两个元素具有相同的频率,则它们应该以升序出现。例如,给定输入:[6, 1000, 3, 3, 1000, 6, 6, 6],输出应为:[6, 6, 6, 6, 3, 3, 1000, 1000]。还必须将元素排序到位,而不是返回新列表。

到目前为止,我已经创建了键和值的HashMap,其中键是元素,值是频率。但我不太确定下一步该怎么做:

public static void method(List<Integer> items)
{
        int size = items.size();
        int count = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < size; ++i)
        {
            int item = items.get(i);
            if (map.containsKey(item))
            {
                map.put(item, map.get(item) + 1);
            }
            else
            {
                map.put(item, 1);
            }
        }
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator()
        {
            public int compare(Object o1, Object o2)
            {
                return ((Comparable) ((Map.Entry) (o1)).getValue())
                .compareTo(((Map.Entry) (o2)).getValue());
            }
        });
        HashMap sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();)
        {
            Map.Entry entry = (Map.Entry) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
}
java sorting hashmap frequency comparator
2个回答
0
投票
public static void method(List<Integer> list) {
    Map<Integer, Long> map = list.stream()
                                 .collect(Collectors.groupingBy(Function.identity(), 
                                                                Collectors.counting()));
    list.sort(new Comparator<Integer>() {
         @Override
         public int compare(Integer o1, Integer o2) {
             Integer cnt1 = map.get(o1);
             Integer cnt2 = map.get(o2);
             int compare = cnt2.compareTo(cnt1);
             if (compare == 0) {
                 return o1.compareTo(o2);
             }
             return compare;
         }
    });
}

0
投票

您可以按以下方式内联排序:

public static void sortInline(List<Integer> list) {
    Map<Integer, Long> map = list.stream()
            .collect(Collectors.groupingBy(Function.identity(),
                    Collectors.counting())); // frequency map
    Comparator<Integer> frequencyComparison = Comparator
            .<Integer>comparingLong(map::get).reversed(); // sort the entries by value in reverse order 
    list.sort(frequencyComparison.thenComparing(Comparator.naturalOrder())); // then by key for the collisions
}
© www.soinside.com 2019 - 2024. All rights reserved.