This is the fourth solution to reverse each word of given line of strings. This program uses the map() method of java stream, and reverse() method of StringBuffer.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.stream.Collectors;
public class ReverseEachWordOfStringUsingStream {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner inpScan = new Scanner(System.in);
System.out.print("Enter an input line of strings= ");
String inpStr = inpScan.nextLine();
String[] arrStrs = inpStr.split("\\s+");
ArrayList<StringBuffer> arrListStrs = new ArrayList<StringBuffer>();
for (String str : arrStrs)
arrListStrs.add(new StringBuffer(str));
//Applying map() of stream, and reverse () of string buffer
arrListStrs.stream().map(s -> s.reverse()).collect(Collectors.toList());
System.out.print("The given line after reversal of each word = ");
for (StringBuffer str : arrListStrs)
System.out.print(str + " ");
}
}
OUTPUT-
Enter an input line of strings= How are you all ?
The given line after reversal of each word = woH era uoy lla ?

Leave a comment