System.out.println(" AA BB".replaceAll("\\s+", " ").trim());
Output:
AA BB
Note. Unlike some other solutions here, it also replaces one tab with one space. If you do not have tabs, you can use "{2,}", and this will be even faster:
System.out.println(" AA BB".replaceAll(" {2,}", " ").trim());
source
share