
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements