繁体   English   中英

在 Java 中对元素进行原地排序

[英]Sorting Elements in Place in Java

我正在尝试通过降低频率对给定元素的列表进行排序。 如果两个元素具有相同的频率,它们应该以递增的顺序出现。 例如,给定输入: [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());
        }
}

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

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
}
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) {
             Long cnt1 = map.get(o1);
             Long cnt2 = map.get(o2);
             int compare = cnt2.compareTo(cnt1);
             if (compare == 0) {
                 return o1.compareTo(o2);
             }
             return compare;
         }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM