Learnitweb

Java Program reverse each word in a String

You can reverse each word in a string using Java 8 Streams by splitting the string into words, reversing each word, and then joining them back.

import java.util.Arrays;
import java.util.stream.Collectors;

public class ReverseEachWord {
    public static void main(String[] args) {
        String sentence = "Java 8 streams are powerful";

        String result = Arrays.stream(sentence.split(" ")) // Split words
                .map(word -> new StringBuilder(word).reverse().toString()) // Reverse each word
                .collect(Collectors.joining(" ")); // Join back to a sentence

        System.out.println(result);
    }
}

Output:

avaJ 8 smaerts era lufrewop