简体   繁体   English

对元素仍处于第一个位置的列表进行排序

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

I have a String list:我有一个字符串列表:

List<String> listString  = new ArrayList<String>();
listString.add("faq");
listString.add("general");
listString.add("contact");

I do some processing on the list and I want to sort this list but I want "general" to always end up in first position.我对列表做了一些处理,我想对这个列表进行排序,但我希望“一般”总是排在第一位。 Thx ;)谢谢 ;)

I like @Petar's approach, but another approach would be to sort it using a custom Comparator that always said that "general" was before whatever it was being compared to.我喜欢@Petar 的方法,但另一种方法是使用自定义比较器对其进行排序,该比较器总是说“一般”在被比较之前。

Collections.sort(list, new Comparator<String>()
  {
     int compare(String o1, String o2)
     {
         if (o1.equals(o2)) // update to make it stable
           return 0;
         if (o1.equals("general"))
           return -1;
         if (o2.equals("general"))
           return 1;
         return o1.compareTo(o2);
     }
});

Do Collections.sort on its subList instead.改为在其subList上执行Collections.sort

    List<String> list = new ArrayList<String>(
        Arrays.asList("Zzz...", "Two", "One", "Three")
    );
    Collections.sort(list.subList(1, list.size()));
    System.out.println(list);
    // "[Zzz..., One, Three, Two]"

API links接口链接

  • subList(int fromIndex, int toIndex)
    • Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.返回此列表中指定的fromIndextoIndex之间的部分的视图。 The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.返回列表受此列表支持,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。 The returned list supports all of the optional list operations supported by this list.返回的列表支持此列表支持的所有可选列表操作。

If the special element is not at index 0, then simply put it there before you sort it as follows:如果特殊元素不在索引 0 处,则只需将其放在那里,然后按如下方式对其进行排序:

    List<String> list = new ArrayList<String>(
        Arrays.asList("Four", "Five", "Zzz...", "Two", "One", "Three")
    );
    Collections.swap(list, list.indexOf("Zzz..."), 0);
    Collections.sort(list.subList(1, list.size()));
    System.out.println(list);
    // "[Zzz..., Five, Four, One, Three, Two]"

API links接口链接

对列表进行排序而不在其中包含“常规”,然后将其添加到开头。

You can use the following code snippet but it might have perfomance/memory problems for the very big lists.您可以使用以下代码片段,但对于非常大的列表,它可能存在性能/内存问题。

public static List<String> sortSpecial(List<String> list, final String alwaysOnTopItem) {
    list.remove(alwaysOnTopItem);
    Collections.sort(list);

    List<String> result = new ArrayList<String>(list.size() + 1);
    result.add(alwaysOnTopItem);
    result.addAll(list);

    return result;
}

public static void main(String[] args) {
    List<String> listString = new ArrayList<String>();
    listString.add("faq");
    listString.add("general");
    listString.add("contact");
    String alwaysOnTopItem = "general";
    List<String> sortedList = sortSpecial(listString, alwaysOnTopItem);
    System.out.println(sortedList);
}

Nice!好的! Question.题。 If we want to fix the positions for the first and last elements then we can enhance the @Paul Tomblin's approach as like below one.如果我们想固定第一个和最后一个元素的位置,那么我们可以增强@Paul Tomblin's方法,如下所示。 Please copy the code and try it.请复制代码并尝试。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CustomComparatorToFixedPosition {

  public static void main(String[] args) {
    List<Emp> empNames = new ArrayList<>();
    empNames.add(new Emp("name1"));
    empNames.add(new Emp("LastName"));
    empNames.add(new Emp("name2"));
    empNames.add(new Emp("FirstName"));
    empNames.add(new Emp("name3"));
    getSortedName(empNames).stream().forEach(emp -> System.out.println(emp.getName()));
  }

  public static List<Emp> getSortedName(List<Emp> empNames) {
    String first = "FirstName";
    String last = "LastName";
    Collections.sort(empNames, new Comparator<Emp>() {
      public int compare(Emp o1, Emp o2) {
        if (o1.getName().equalsIgnoreCase(first) || o2.getName().equalsIgnoreCase(last))
          return -1;
        if (o2.getName().equalsIgnoreCase(first) || o1.getName().equalsIgnoreCase(last))
          return 1;
        return o1.getName().compareTo(o2.getName());
      }
    });
    return empNames;
  }
}

class Emp {

  private String name;

  Emp(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}

暂无
暂无

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

相关问题 对元素仍在最后位置的列表进行排序 - Sort a list with a element still in last position 按第一个元素对字符串数组列表进行排序 - Sort List of string arrays by first element 使用 Stream 将列表中的元素移动到第一个 position - Move an element in the list to the first position using Stream 如何声明元素在列表中的位置(确认它是列表中的第一个元素) - How to assert position of element on the list (Confirm it is first element on the list) 如何排序列表<List<String> &gt; 按每个列表的第一个元素? - How to sort List<List<String>> by first element of every list? 将 Map 的第一个元素添加到第一个 Position 的另一个列表中,依此类推...第二个 map 元素到第二个 Z4757FE07FD492ADBEEAZ6 列表中 - Add first element of Map into another list at 1st Position and so on…second map element into second position of list 按第一个元素对对象列表进行排序,但如果相等则按第二个元素排序 - Sorting a List of objects by the First element but if Equal sort by the second 在第一个 position 插入元素时返回不正确的链接列表 - Incorrect Linked List being returned when inserting element at first position 如何按日期排序列表,然后在第一个位置搜索元素和设置 - How to order a list by date and then search a element and setting at first position 排序后arraylist中的元素位置 - element position in arraylist after sort
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM