This is the third solution to reverse each word in the given input sentence. This program uses the Single Abstract method, which implemented by using Lambda expression.
import java.util.StringTokenizer;
//Define the functional interface with SAM 'ReverseEachWord'
interface ReverseEachWord {
public StringBuffer reverseword(String str);
}
public class ReverseEachString {
public static void main(String[] args) {
/*
* Define the Lambda expression for the functional interface 'ReverseEachWord'
*/
ReverseEachWord Rew = ((Sentence) -> {
// Process each word in a Sentence, and store in 'resultStr' StringBuffer variable
StringTokenizer allWords = new StringTokenizer(Sentence);
StringBuffer resultStr = new StringBuffer();
while (allWords.hasMoreTokens()) {
StringBuffer nextWord = new StringBuffer(allWords.nextToken());
resultStr.append(nextWord.reverse() + " ");
}
return resultStr;
});
System.out.println("Reversing each word of 'How are you' :" + Rew.reverseword("How are you"));
System.out.println("Reversing each word of 'This program uses Lambda expression' :"
+ Rew.reverseword("This program uses Lambda expression"));
System.out.println("Reversing each word of 'StringBuffer supports reverse method' :"
+ Rew.reverseword("StringBuffer supports reverse method"));
System.out.println("Reversing each word of 'Executed without any errors' :"
+ Rew.reverseword("Executed without any errors"));
}
}
OUTPUT:-
Reversing each word of 'How are you' :woH era uoy
Reversing each word of 'This program uses Lambda expression' :sihT margorp sesu adbmaL noisserpxe
Reversing each word of 'StringBuffer supports reverse method' :reffuBgnirtS stroppus esrever dohtem
Reversing each word of 'Executed without any errors' :detucexE tuohtiw yna srorre

Leave a comment