Thursday, April 9, 2015

Sort Collection using sort function and Java 8

Goal
Sorting is widely used in daily routine to modify data arrangement. In this blog the input is a list of alphabets. Using Java 8 and new sort method. This blog introduces List.sort() as a small example.

Setup
Lets start with following code. As shown it prints unsorted array elements.

         @Test
    public void testCollectionSorted() {
        List list = Arrays.asList("b", "f", "e", "a");
        
        // print each elements of list object
        list.forEach(input -> System.out.println(input));
    }

Solution
Now we will use List.sort() and pass a lambda expression which will sort the list

list.sort((e1e2) -> {
            return e1.compareTo(e2);
        });

Thats it. Here is the full method which can be used to sort and print array contains alphabets.

         @Test
    public void testCollectionSorted() {
        
        List list = Arrays.asList("b", "f", "e", "a");
        list.sort((e1, e2) -> {
            return e1.compareTo(e2);
        });

        list.forEach(input -> System.out.println(input));
}

No comments:

Post a Comment