Reverse a String in Java Using Lambda Expression
In Java, a String is an immutable object that represents a series of characters. The charAt() function of the String class can be used to extract characters from a user-entered string and append them in reverse order to reverse the string.
In the example below, the Scanner class is used to reverse a string using a lambda expression.
There are several techniques to reverse a string in Java. You can use the StringBuffer() class and reverse String even in Java 8.
However, we may also do this by using lamda expressions.
Here's an example I'm using a string array, and I've reversed each string in the array. It does not utilise the Stream API:
String[] Strarr = new String{ "abc," "def" ,"ghi"};
Arrays.asList(stringArray).
s = new StringBuilder replaceAll (s).
reverse().toString());
// Reversed Strings will now make up stringArray.
Strlambda.java
import java.util.Scanner;
import java.io.*;
interface Strfun {
String func(String n);
}
public class Strlambda {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
Strfun rev = (str) -> { // lambda expression
String ans = "";
for(int x = str.length()-1; x >= 0; x--)
ans += str.charAt(x);
return ans;
};
System.out.println("Reverse word in lambda function " + rev.func("manoj kumar mamilla"));
System.out.println("Enter a string that is to be reversed :");
String word = scan.nextLine();
System.out.println(word +" After reversing is : " + rev.func(word));
}
}
Output:
Reverse word in lambda function allimam ramuk jonam
Enter a string that is to be reversed :
Hello manoj kumar
Hello manoj kumar After reversing is : ramuk jonam olleH
Example1:
Strlambda1.java
import java.util.*;
import java.util.stream.*;
public class Strlambda1{
public static void main(String []args){
String i = "Hello manoj kumar";
Iterator<Character> itr = i.chars()
.mapToObj(item -> new Character((char)item))
.collect(Collectors.toCollection(ArrayDeque::new))
.descendingIterator();
String ans = StreamSupport
.stream(Spliterators.spliteratorUnknownSize(itr, Spliterator.ORDERED), false)
.map(Object::toString)
.collect(Collectors.joining(""));
System.out.println(ans);
}
}
Output:
ramuk jonam olleH