[Java 8] – New method Sort in List

Now you can use this method sort when you have a List Object and want sort this.

If you only call the sort() such “myList.sort()” the list will be sort by ascendant (A – Z). Also to define other way to sort you can use a parameter, you can implement your comparator.

Example :

@Test
public void myMethod(){

    List<String> words = new ArrayList<String>();
    words.add("xxxxxxxlargesize");
    words.add("small");
    words.add("mediumsize");
    
    Comparator myComparator = new MyComparator();
    words.sort(myComparator); // Order by myComparator

    words.forEach(new Consumer<String>(){
        public void accept(String w) {
            System.out.println(w);
        }
    });
}

//    * @return a negative integer, zero, or a positive integer as the
//    *         first argument is less than, equal to, or greater than the
//    *         second.
public class MyComparator implements Comparator<String> {
    @Override
    public int compare(String s1, String s2) {
        if(s1.length() < s2.length())
            return -1;
        if(s1.length() > s2.length())
            return 1;
        return 0;
    }
}

For you now more look the new method in List Class:

@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    Arrays.sort(a, (Comparator) c);
    ListIterator<E> i = this.listIterator();
    for (Object e : a) {
        i.next();
        i.set((E) e);
    }
}

 

*** Important, the default methods are new too. But this is subject for other post 😛

 

Now the same code but better 😛 With lambdas

public void myMethod(){

    List<String> words = new ArrayList<String>();
    words.add("xxxxxxxlargesize");
    words.add("small");
    words.add("mediumsize");
    words.sort((s1, s2) -> Integer.compare(s1.length(),s2.length()));
    words.forEach(s -> System.out.println(s)); 

}

You can use to :

words.sort(Comparator.comparing(s -> s.length()));

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s