how to sort an ArrayList in ascending order using Collections and Comparator

后端 未结 6 789
轮回少年
轮回少年 2020-12-06 07:36

How to sort an ArrayList in ascending order using Comparator? I know how to sort it in descending order using:

Comparator mycompar         


        
6条回答
  •  伪装坚强ぢ
    2020-12-06 08:27

    Sort By Value

      public Map sortByValue(Map map, final boolean ascending) {
                Map result = new LinkedHashMap();
                try {
                    List list = new LinkedList(map.entrySet());
    
                    Collections.sort(list, new Comparator() {
                        @Override
                        public int compare(Object object1, Object object2) {
                            if (ascending)
                                return ((Comparable) ((Map.Entry) (object1)).getValue())
                                        .compareTo(((Map.Entry) (object2)).getValue());
                            else
                                return ((Comparable) ((Map.Entry) (object2)).getValue())
                                        .compareTo(((Map.Entry) (object1)).getValue());
    
                        }
                    });
    
                    for (Iterator it = list.iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        result.put(entry.getKey(), entry.getValue());
                    }
    
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                }
    
                return result;
            }
    

提交回复
热议问题