Determine if a list composed of anagram elements in Java 8

  • A+

I want to determine if a list is anagram or not using Java 8.

Example input:

"cat", "cta", "act", "atc", "tac", "tca" 

I have written the following function that does the job but I am wondering if there is a better and elegant way to do this.

boolean isAnagram(String[] list) {     long count = Stream.of(list)             .map(String::toCharArray)             .map(arr -> {                 Arrays.sort(arr);                 return arr;             })             .map(String::valueOf)             .distinct()             .count();     return count == 1;  } 

It seems I can't sort char array with Stream.sorted() method so that's why I used a second map operator. If there is some way that I can operate directly on char stream instead of Stream of char array, that would also help.


Instead of creating and sorting a char[] or int[], which can not be done inline and thus "breaks" the stream, you could get a Stream of the chars in the Strings and sort those before converting them to arrays. Note that this is an IntSteam, though, and String.valueOf(int[]) will include the array's memory address, which is not very useful here, so better use Arrays.toString in this case.

boolean anagrams = Stream.of(words)         .map(String::chars).map(IntStream::sorted)         .map(IntStream::toArray).map(Arrays::toString)         .distinct().count() == 1; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: