Sorting a list with the element still in first position
I have a list of strings:
List<String> listString = new ArrayList<String>();
listString.add("faq");
listString.add("general");
listString.add("contact");
I'm doing some processing on a list, and I want to sort that list, but I want "general" to always be in the first position. thanks;)
+2
a source to share
4 answers
I like @Petar's approach, but another approach would be to sort it using a custom Comparator, which always said "general" was before it was compared.
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);
}
});
+12
a source to share
Do Collections.sort
instead subList
.
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 references
-
subList(int fromIndex, int toIndex)
- Returns a representation of the portion of this list between the specified
fromIndex
, inclusive andtoIndex
exclusive. The returned list is maintained by this list, so non-structural changes to the returned list are reflected in this list and vice versa. The returned list supports all additional list operations supported by this list.
- Returns a representation of the portion of this list between the specified
If the special item is not at index 0, just put it there before sorting it like this:
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 references
-
Collections.swap(List<?> list, int i, int j)
- Collapses items at the specified positions in the specified list.
+15
a source to share
You can use the following code snippet, but it may have performance / memory issues for very large 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);
}
+1
a source to share