Program to sort array of strings – Java 8 Lambda Stream

  • Given an array of strings in java.
  • We would like to sort an array of strings in alphabetical order using Java8 Lambda Stream.

Examples: Sort array of strings in alphabetical order

Example : 

Given an Input Array : [Java, Python, ReactJS, Angular, C#]

Output of program should be [Angular, C#, Java, Python, ReactJS]

Method to sort stream in natural order

Method Name Description
Stream<T> sorted() Returns a stream consisting of the elements of this stream, sorted according to natural order.

Algorithm: sort array of string in alphabetical order

  1. Given an array of string.
  2. Get Java 8 Stream using Arrays.stream method of Arrays class.
  3. Sort sequential stream using sorted method of stream.
  4. Collect sequential stream in array of strings.
  5. Print array of string using Arrays.toString method.

Code: sort array of string in alphabetical order – lambda stream

package org.learn.beginner;

import java.util.Arrays;

public class SortStringArray {

    public static void main(String[] args) {

        String [] arrString = {"Java",
                                "Python",
                                "ReactJS",
                                "Angular",
                                "C#"};

        System.out.println("Input Array : "+ Arrays.toString(arrString));
        arrString = Arrays.stream(arrString)
                .sorted()
                .toArray(String[]::new);

        System.out.println("Sorted Array : "+ Arrays.toString(arrString));
    }
}

Output: sort array of string in alphabetical order

Input Array : [Java, Python, ReactJS, Angular, C#]
Sorted Array : [Angular, C#, Java, Python, ReactJS]
Scroll to Top