Using compareTo and Collections.sort

前端 未结 4 1328
太阳男子
太阳男子 2021-01-06 18:27

I have a franchise class with owner(owner of franchise\'s name), state(2-character string for the state where the franchise is located), and sales (total sales for the day)<

4条回答
  •  难免孤独
    2021-01-06 18:51

    Comparable will give only one way of comparision. This can be done using Comparator interface.

    Collections.sort(list, new Comparator() {
    @Override
                public int compare(Franchise obj1, Franchise obj2) {
                    if(obj1.getState().compareTo(obj2.getState()) == 0)
                    {
                        Double a1 =obj1.getSales();
                        Double a2 = obj2.getSales();
                        return a2.compareTo(a1);
                    }
    
                        return o1.getName().compareTo(o2.getName());
            } 
    }
    

提交回复
热议问题