Arrange words of a sentence in alphabetical order in java

Let’s learn to arrange words of a sentence in alphabetical order in java.

Arrange words of a sentence in alphabetical order in java

In the below example we are using collection to arrange words of a sentence in alphabetical order.

Here’s the program to arrange words of a sentence in alphabetical order in java.

import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class ArrangeInAlphabeticalOrder 
{
   public static void main(String[] args) 
   {
      Set set = new TreeSet();
      String strInput = "hi all welcome to flower brackets blog";
      System.out.println("Before arranging sentence in alphabetical order: " + strInput);
      StringTokenizer strToken = new StringTokenizer(strInput," ");
      while(strToken.hasMoreElements())
      {
         set.add(strToken.nextElement());
      }
      System.out.println("After arranging sentence in alphabetical order: " + set);
   }
}


Output:

Before arranging sentence in alphabetical order: hi all welcome to flower brackets blog
After arranging sentence in alphabetical order: [all, blog, brackets, flower, hi, to, welcome]


Also read – access modifiers in java