Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list with element still in first position

Tags:

java

list

sorting

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 ;)

like image 801
Mercer Avatar asked Nov 26 '22 21:11

Mercer


1 Answers

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.

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);
     }
});
like image 105
Paul Tomblin Avatar answered Dec 15 '22 04:12

Paul Tomblin