如何使用在java

时间:2017-03-15 15:51:14

标签: java

如何使用在java中设置值的字符串和整数对通用哈希映射进行排序:

这里是答案,但需要找出一种优化的方法。

    HashMap<String,Integer> hash = new HashMap<String,Integer>();
    hash.put("king", 2);
    hash.put("Queen", 3);
    hash.put("Pawn", 1);
    hash.put("Minister", 7);
    hash.put("Horse", 6);

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

    Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
         public int compare( Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2 )
            {
                return (o1.getValue()).compareTo( o2.getValue() );
            }
    });

     Map<String,Integer> result = new LinkedHashMap<String,Integer>();

     for (Map.Entry<String,Integer> entry : list)
        {
            System.out.println( entry.getKey()+" === "+entry.getValue() );
        }    

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,那么优化并不多,除了为有序的而不是HashMap更改你的集合。

您的代码并不是很糟糕,复杂性是由List<Map.Entry<String,Integer>> list = LinkedList<Map.Entry<String,Integer>>( hash.entrySet());

引起的 n log(n)的顺序

否则,您可以通过不创建新集合并从有序集合开始来避免一个步骤。 #include "Draw.h" #include "qpushbutton.h" #include "qradiobutton.h" #include "qgroupbox.h" Draw::Draw(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); //Invisible elements ui.frmAbsolut->setVisible(false); //We create the connections to methods connect(this->ui.myradiobutton1, SIGNAL(toggled(bool)), this, SLOT(on_rdbMethod_change(this->ui.myradiobutton1->isChecked, 0))); } void Draw::on_rdbMethod_change(bool value, int option) { //0: frmAbsolut printf("%d \n", option); if (value == true){ if (option == 0) { this->ui.frmAbsolut->setVisible(true); } } }