While your indentation is good, the placement of whitespace isn't very good yet. In Java, we tend to put whitespace after keywords and before braces. A beautifier with standard settings would make your code more readable already.
Use the most common type that still does the job.
For example, your variable
map should be declared as
Smarter Use of
Instead of getting the list, checking whether it's
null and if it isn't
null, creating it, and then always putting it, you could use
Map.computeIfAbsent(), like this:
.computeIfAbsent(normalizedAnagram, s -> ArrayList::new)
Split your logic
getAnagramsTogether is doing many things. You could split it into multiple methods. For example, you could have a separate method
normalizeAnagram() which takes a
String and returns a new
String with the characters sorted.
Bug in your call to
It should be noted that
char is NOT a character. It is a UTF-16 fragment. For the first Unicode plane, i.e. code points with values that can be represented by 16 bits,
char is a character. But for code points with higher values, a
char contains only part of the character, and the way how you construct the normalized anagram is tearing characters apart.
It may not matter to you, as probably all relevant words in your use cases would have code points in the 16 bit plane.
You should be consistent, either use
StringBuilder.append() doesn't make sense.
StringBuilder in order to have
String-concatenation which is faster and uses less memory than using
+ in an argument to
StringBuilder.append() is completely contrary to the intention of using
StringBuilder in the first place.
Don't construct the same object twice.
new String(wordArray) twice for no good reason.
You could just create a single
String normalizedAnagram and use that.
Consider a smarter way of String concatenation.
The following code concatenates your final Map into a String in a smarter way:
.flatMap(entry -> entry.getValue().stream())