ビーニー・レオン:
私は周波数を減少させることによって与えられた要素のリストをソートしようとしています。二つの要素が同じ周波数を持っている場合、彼らは昇順で表示されます。例えば、入力が与えられる:[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
}