There are following way to Check if two Strings are Anagrams of each other in java 8.
- Here str1.split(“”) method splits the string into an array of substrings and stream this array using Arrays.stream() method.
- In map(a->a.toUpperCase()) we convert all characters to uppercase.
- From sorted () method sort the characters in ascending order.
- After Collectors.joining() method collect all characters into string.
- Next validate if r1 is equals to r2 or not. if it equals then String is Anagrams otherwise not.
import java.util.Arrays;
import java.util.stream.Collectors;
public class CheckAnagram {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
String r1 = Arrays.stream(str1.split("")).map(a -> a.toUpperCase()).sorted().collect(Collectors.joining());
String r2 = Arrays.stream(str2.split("")).map(a -> a.toUpperCase()).sorted().collect(Collectors.joining());
if (r1.equals(r2)) {
System.out.println("it is a anagram string");
} else {
System.out.println("it is a not anagaram string");
}
}
}
Output :-
it is a anagram string