# Sort an array of strings according to string lengths using Map

Given an array of strings, we need to sort the array in increasing order of string lengths, using Map Data Structure.

Examples:

Input: str[] = {“GeeksforGeeeks”, “I”, “from”, “am”}
Output: I am from GeeksforGeeks

Input: str[] = {“You”, “are”, “beautiful”, “looking”}
Output: You are looking beautiful

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The given approach is for Java using TreeMap

Below is the implementation of the above approach:

 `// Java program to sort an Array of ` `// Strings according to their lengths ` `// using Map ` ` `  `import` `java.util.*; ` `import` `java.util.Map.Entry; ` `import` `java.io.*; ` ` `  `public` `class` `GFG { ` ` `  `    ``// Function to Sort the array of string ` `    ``// according to lengths using Map ` `    ``static` `String[] sort(String[] str, ``int` `n) ` `    ``{ ` `        ``TreeMap > map ` `            ``= ``new` `TreeMap >(); ` ` `  `        ``for` `(``int` `i = ``0``; i < n; i++) { ` ` `  `            ``map.putIfAbsent(str[i].length(), ` `                            ``new` `ArrayList()); ` `            ``map.get(str[i].length()).add(str[i]); ` `        ``} ` ` `  `        ``int` `temp = ``0``; ` ` `  `        ``for` `(Entry > ` `                 ``e : map.entrySet()) { ` ` `  `            ``for` `(``int` `i = ``0``; i < e.getValue().size(); i++) { ` ` `  `                ``str[temp] = e.getValue().get(i); ` `                ``temp++; ` `            ``} ` `        ``} ` `        ``return` `str; ` `    ``} ` ` `  `    ``// Function to print the sorted array of string ` `    ``static` `void` `printArraystring(String str[], ``int` `n) ` `    ``{ ` `        ``for` `(``int` `i = ``0``; i < n; i++) ` `            ``System.out.print(str[i] + ``" "``); ` `    ``} ` ` `  `    ``// Driver function ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``String[] arr = { ``"GeeksforGeeks"``, ` `                         ``"I"``, ``"from"``, ``"am"` `}; ` `        ``int` `n = arr.length; ` ` `  `        ``// Function to perform sorting ` `        ``arr = sort(arr, n); ` ` `  `        ``// Calling the function to print result ` `        ``printArraystring(arr, n); ` `    ``} ` `} `

Output:

```I am from GeeksforGeeks
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.