How about below tree map:
Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
What ever you put in this sortedMap it will be sorted automatically.
First of all TreeMap
is sorted implementation of Map
Interface.
There is a but as it sorts keys on [natural order fashion][https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html]. As Java doc says String
type is a Lexicographic Natural order type. Imagine the below list of numbers with String type. means below list will be sorted not as expected.
List<String> notSortedList = List.of("78","0", "24", "39", "4","53","32");
If you just you the default TreeMap
constructor like below and push each element one-by-one like below:
Map<String, String> map = new TreeMap<>();
for (String s : notSortedList) {
map.put(s, s);
}
System.out.println(map);
output is: {0=0, 14=14, 24=24, 32=32, 39=39, 4=4, 48=48, 53=53, 54=54, 78=78}
As you see number 4 for example comes after '39'. This is the nature of the Lexicographic data types like String. If that one was an Integer data type then that was okay though.
To fix this use argument to first check the length of the String and then compare them. In java 8 is done like this:
Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
It first compare each element by length then apply check by compareTo
as the input the same as the element to compare with.
If you prefer to use a more understandable method, the above code will be equivalent with below code:
Map<String, String> sortedMap = new TreeMap<>(
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int lengthDifference = o1.length() - o2.length();
if (lengthDifference != 0) return lengthDifference;
return o1.compareTo(o2);
}
}
);
Because the TreeMap
constructor accepts the comparator Interface you can build up any even more complex implementation of Composite classes.
This is also another form more simplified version.
Map<String,String> sortedMap = new TreeMap<>(
(Comparator<String>) (o1, o2) ->
{
int lengthDifference = o1.length() - o2.length();
if (lengthDifference != 0) return lengthDifference;
return o1.compareTo(o2);
}
);