在HashMap中交换特定的<key,value>

时间:2018-05-20 07:07:17

标签: java sorting java-8 hashmap mapping

我使用<String,Integer>,姓名(唯一)和成绩的映射。 我排序所以最高等级排在第一位(以其关键值)。 但是,如果两个等级相同,我需要按字母顺序打印。

到目前为止,我得到了这个,按值降序排序:

public  <String, Integer extends Comparable<? super Integer>> Map<String, Integer> sortByValue(Map<String, Integer> map) {
    List<Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
    list.sort(Entry.comparingByValue());



    //actually need descending order, so use comparator to change from natural ordering
    Comparator comparator = Collections.reverseOrder();
    list.sort(Entry.comparingByValue(comparator));


    Map<String, Integer> result = new LinkedHashMap<>();
    for (Entry<String, Integer> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return results;
}

我试图通过复制到ArrayList来工作,尽管我觉得自己走到了尽头:

   List<String> listnames = new ArrayList<>();
    for(String names :  result.keySet()){
        listnames.add(names);
    }
    List<Integer> listgrades = new ArrayList<>();
    for(Integer grades :  result.values()){
        listgrades.add(grades);
    }


for (int i = 0 ; i<result.size() ; i ++){
    if(listgrades.get(i).equals(listgrades.get(i+1))){
        result.get(listgrades.);
        //.....

    }
}

任何帮助/提示赞赏!

2 个答案:

答案 0 :(得分:0)

您可以同时按两个属性进行排序:

Comparator<Entry<String, Integer>> comparator = Comparator.comparing(Entry::getValue);
Comparator<Entry<String, Integer>> comparator2 = comparator.reversed(); // Here sort the grade in reversed order (highest come first)
Map<String, Integer> sortedMap = map.entrySet().stream()
                  .sorted(comparator2.thenComparing(Entry::getKey))
                  .collect(toMap(Entry::getKey, Entry::getValue,
                           (v1, v2) -> v2, LinkedHashMap::new));

您通过引入Map来使事情变得更复杂。

您可以对List<Student> Student {name; grade}

@SuppressWarnings("JniMissingFunction")做同样的事情

答案 1 :(得分:0)

根据你的陈述,它将有助于定义一些基本类,以包含你想要实现的目标。

然后定义自定义比较器类以执行自定义排序。

class Student
{
    String name;
    int grade;

    // Constructor
    public Student(String name, int grade)
    {
        this.name = name;
        this.grade = grade;
    }

    // Used to print student details in main()
    public String toString()
    {
        return ""+String.format("%-10s - %3d",this.name, this.grade); 
    }
}

class SortbyGradedescNameAsc implements Comparator<Student>
{
    // Used for sorting in 
    // Descending order of grade, then 
    // Ascending order of Name 
    public int compare(Student a, Student b)
    {
        int result = b.grade - a.grade;
        if (result != 0) {
            return result;
        }else{
            return a.name.compareTo(b.name);
        }
    }
}

public class Main{

     public static void main(String []args){

        ArrayList<Student> ar = new ArrayList<Student>();
        ar.add(new Student( "bob", 60));
        ar.add(new Student( "ted", 70));
        ar.add(new Student( "gord", 80));
        ar.add(new Student( "fred", 90));
        ar.add(new Student( "sam", 70));
        ar.add(new Student( "maggie", 70));
        ar.add(new Student( "alfred", 50));
        ar.add(new Student( "adam", 50));

        System.out.println("-- Unsorted --");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));

        Comparator c = new SortbyGradedescNameAsc();
        Collections.sort(ar, c);

        System.out.println(" -- grade sorted descending then name sorted ascending --");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));

     }
}

- 下面的输出 -

-- Unsorted --
bob        -  60
ted        -  70
gord       -  80
fred       -  90
sam        -  70
maggie     -  70
alfred     -  50
adam       -  50
-- grade sorted Descending then name sorted Ascending --
fred       -  90
gord       -  80
maggie     -  70
sam        -  70
ted        -  70
bob        -  60
adam       -  50
alfred     -  50