How to reverse a string using lambda expression in Java?


A String is an object that represents a sequence of characters and immutable in Java. We can reverse a string entered by the user using the charAt() method of String class to extract characters from the string and append them in reverse order to reverse the entered string.

In the below example, we need to reverse a string using lambda expression with the help of the Scanner class.

Example

import java.util.Scanner;

interface StringFunc {
   String func(String n);
}
public class StringFuncLambdaTest {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      StringFunc reverse = (str) -> {   // lambda expression
         String result = "";
         for(int i = str.length()-1; i >= 0; i--)
            result += str.charAt(i);
         return result;
      };
      System.out.println("Lambda reversed is: " + reverse.func("Lambda Expression"));
     
      System.out.println("Enter a word to reverse a String:");
      String word = sc.nextLine();
      System.out.println(word +" in reversed form - " + reverse.func(word));
   }
}

Output

Lambda reversed is: noisserpxE adbmaL
Enter a word to reverse a String:
TutorialsPoint
TutorialsPoint in reversed form - tnioPslairotuT

Updated on: 13-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements