给定一个字符串数组,我们需要使用Map Data Structure按字符串长度的升序对数组进行排序。
例子:
Input: str[] = {“GeeksforGeeeks”, “I”, “from”, “am”}
Output: I am from GeeksforGeeks
Input: str[] = {“You”, “are”, “beautiful”, “looking”}
Output: You are looking beautiful
方法:给定的方法适用于使用TreeMap的Java
- 取一个TreeMap,它将包含字符串的长度作为键,并包含一个与键的长度相同的String ArrayList。
- 由于我们知道TreeMap已经排序,因此在插入TreeMap之后,我们再次将值(来自ArrayList的字符串)一个一地取出到Strings Array中。
下面是上述方法的实现:
// 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);
}
}
输出:
I am from GeeksforGeeks