简体   繁体   English

对元素仍在最后位置的列表进行排序

[英]Sort a list with a element still in last position

I have list of objects with data.我有包含数据的对象列表。 I want the the particular object alone to stay last in the list when I am doing sorting.当我进行排序时,我希望特定对象单独留在列表中。 But its coming at the very first now.但它现在最先出现。

Present:当前的:

Archived存档
Application应用
Run - time etc运行时间等
Embedded Components IDE -嵌入式组件 IDE -
Debug, Compile and Build Tools调试、编译和构建工具
Initialization/Boot/Device Driver初始化/引导/设备驱动程序

Required必需的

Application应用
Run - time etc运行时等
Embedded Components IDE -嵌入式组件 IDE -
Debug, Compile and Build Tools调试、编译和构建工具
Initialization/Boot/Device Driver初始化/引导/设备驱动程序
Archived存档

Collections.sort(existingList,new Comparator<Map<String, Object>>() {
  public int compare(Map<String, Object> o1,Map<String, Object> o2) {
    String archiveCheck = (String)o1.get("name");
    if(archiveCheck.equalsIgnoreCase("Archived"))
        return -10000;
    else
        return ((String) o1.get("name")).compareTo((String) o2.get("name"));
  }
});

Just return positive value whenever o1 is Archived只要o1Archived ,就返回正值

Collections.sort(existingList ,new Comparator<Map<String, Object>>() {
        public int compare(Map<String, Object> o1,Map<String, Object> o2) {
           String name1 = (String)o1.get("name");
           String name2 = (String)o2.get("name");

           if(name1.equalsIgnoreCase("Archived"))
             return 1;
           if(name2.equalsIgnoreCase("Archived"))
               return -1;
           return name1.compareTo(name2);
        }
    });

Edit We have to check the Archived value for both arguments in the Comparator.编辑我们必须检查比较器中两个参数的Archived值。 Updated the answer.更新了答案。 So, in case of second argument matching Archived, then return negative value因此,如果第二个参数匹配存档,则返回负值

A simple solution could be to remove the element you want to keep last from your list (or not add it in the first place), sort the list with its default comparator, then add the element at the end.一个简单的解决方案可能是从列表中删除要保留在最后的元素(或者不首先添加它),使用默认比较器对列表进行排序,然后在末尾添加该元素。

The most simply thing, but not such as effective as you probably need, which occurred to me is the idea about最简单的事情,但没有你可能需要的那么有效,我想到的是关于

  • to iterate over original list - "Archived" copy to some temp , all others copy to newList ..迭代original list - "Archived"复制到一些temp文件,所有其他复制到newList ..
  • Sort newList , and for the last insert "Archived" object (temp) Sort newList ,并为最后插入"Archived"对象(临时)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM