Java how to sort a Linked List?

后端 未结 9 2062
耶瑟儿~
耶瑟儿~ 2020-12-03 03:00

I am needing to sort a linked list alphabetically. I have a Linked List full of passengers names and need the passengers name to be sorted alphabetically. How would one do t

9条回答
  •  忘掉有多难
    2020-12-03 03:25

    In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:

        LinkedListlist = new LinkedList();
        list.add("abc");
        list.add("Bcd");
        list.add("aAb");
    
        list.sort( new Comparator(){
        @Override
            public int compare(String o1,String o2){
                return Collator.getInstance().compare(o1,o2);
            }
        });
    

    References:

    http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

    http://docs.oracle.com/javase/7/docs/api/java/util/List.html

提交回复
热议问题