【问题标题】:How to sort a LinkedHashMap by value without Collections.sort()?如何在没有 Collections.sort() 的情况下按值对 LinkedHashMap 进行排序?
【发布时间】:2019-02-17 16:57:42
【问题描述】:

我正在尝试为 LinkedHashMap/ArrayList 编写选择排序方法,但我遇到了问题,我不确定出了什么问题。它编译但实际上并不对列表进行排序。我正在尝试按值降序排序。任何帮助将不胜感激。

public static List sort(LinkedHashMap<String, Integer> words) {


        List<Map.Entry<String, Integer>> entries = new ArrayList<>(words.size());
        entries.addAll(words.entrySet());

        int max;

        for(int i = 0; i < entries.size(); i++) {

            max = entries.get(i).getValue();

            for(int j = i + 1; j < entries.size(); j++) {

                if (entries.get(j).getValue().compareTo(entries.get(max).getValue()) > 0) {

                    max = entries.get(j).getValue();
                }

            }

            if(max != i) {

                Map.Entry temp1 = entries.get(i);

                entries.set(entries.get(i).getValue(), entries.get(max));

                entries.set(entries.get(max).getValue(), temp1);
            }

        }

        return entries;
    }

【问题讨论】:

  • 似乎在整个代码中,索引和值可以互换使用,max 分配给值,然后与索引进行比较。

标签: java sorting dictionary hashmap selection-sort


【解决方案1】:

您的代码基本上是正确的,您只是在几个地方混淆了值和索引。

你需要更换:

max = entries.get(i).getValue();

max = i;

这个

max = entries.get(j).getValue();

max = j;

entries.set(entries.get(i).getValue(), entries.get(max));
entries.set(entries.get(max).getValue(), temp1);

entries.set(i, entries.get(max));
entries.set(max, temp1);

确保您了解这些更改为何有效。

【讨论】:

  • 我不确定这是否都是错误的。它将最高值放在首位,这是理所当然的,但其余的仍然是加扰的。
  • 是的,错过了一个。我现在已经添加了。
猜你喜欢
  • 2017-05-07
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2014-09-07
相关资源
最近更新 更多