sort and group a java collection

前端 未结 5 447
无人及你
无人及你 2021-02-01 21:17

I have an object which has a name and a score. I would like to sort a collection of such objects so that they are grouped by name and sorted by maximum score in each group (and

5条回答
  •  无人共我
    2021-02-01 22:08

    I think you can do this. First check to see if the group is equal. If it is then compare on score. Otherwise return which group you want to be more on top. Let me code it up.

        class Item{
          String name;
          int score;
        }
    
       new Comparator(){
    
           @Override
           public int compare(Item o1, Item o2) {
                if (o1.name.equals(o2.name)) {
                    return o1.score > o2.score ? 1 : -1; // might have to flip this. I didn't test
                }else {
                    return o1.name.compareTo(o2.name);
                }
           }
        };
    

提交回复
热议问题