Java 8 program that reverses words of a given string

In this short article, we will write a Java 8 program that reverses words of a given string.
We will use Java 8 lambda expression and stream API to write this program.
Learn Java programming at https://www.javaguides.net/p/java-tutorial-learn-java-programming.html.
Learn Java 8 at https://www.javaguides.net/p/java-8.html.

Java 8 program that reverses words of a given string

package com.java.tutorials.programs;

import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class Java8Program {

    private static final Pattern PATTERN = Pattern.compile(" +");
    private static final String WHITESPACE = " ";

    public static void main(String[] args) {

        String input = "Java is my best programming language";
        String output = PATTERN.splitAsStream(input)
            .map(w - > new StringBuilder(w).reverse())
            .collect(Collectors.joining(WHITESPACE));

        System.out.println(" Output => " + output);
    }
}
Output:
 Output => avaJ si ym tseb gnimmargorp egaugnal
 

Comments