When I want to sort data on linked list by using collections.sort()
and comparator will working after write (collections.sort (...)
) and then use it again with comparator?
Is it possible to just use a comparator without collection.sort (...)
first?
public class JavaApplication {
public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.addFirst("0");
System.out.println(lList);
lList.addLast("6");
System.out.println(lList);
lList.addFirst("2");
System.out.println(lList);
lList.add(3, "10");
System.out.println(lList);
lList.add(4,"25");
System.out.println(lList);
getIterator( lList ).add( "60" );
System.out.println(lList);
lList.addLast("10");
System.out.println(lList);
lList.addLast("15");
System.out.println(lList);
lList.add(6,"40");
System.out.println(lList);
getIterator( lList ).add( "70" );
System.out.println(lList);
lList.addFirst("75");
System.out.println(lList);
Collections.sort(lList);
Collections.sort(lList, new AComparator());
System.out.println("LinkedList (after sorting using Comparator): "+lList);
}
private static ListIterator getIterator(LinkedList lList) {
return lList.listIterator( lList.size() / 2 );
}
}
class AComparator implements Comparator<String> {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
And can someone give me a suggest how to efficiency the code.
Output that I want :
Unsorted [75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15]
LinkedList (after sorting using Comparator): [0, 1, 2, 2, 3, 4, 5, 6, 10, 10, 15, 25, 40, 60, 70, 75]