what is the simple way to do lexicographical ordering of string list using guava. I do it this way:
List<String> s = newArrayList(
"susen", "soumen", "dipak", "abhi", "zylo",
"zala", "gautam", "gautom", "shaswasti", "saswati");
List<char[]> ts = newArrayList(transform(s, new Function<String, char[]>() {
@Override
public char[] apply(String input) {
return input.toCharArray();
}
}));
Collections.sort(ts, Chars.lexicographicalComparator());
s = transform(ts, new Function<char[], String>() {
@Override
public String apply(char[] input) {
return String.valueOf(input);
}
});
System.out.println(s);
Split the strings using split() function. After that sort the words in lexicographical order using sort(). Iterate the words through loop and print each word, which are already sorted.
Lexicographical order is nothing but the dictionary order or preferably the order in which words appear in the dictonary. For example, let's take three strings, "short", "shorthand" and "small". In the dictionary, "short" comes before "shorthand" and "shorthand" comes before "small". This is lexicographical order.
Sorting a string array in Lexicographical Order (Dictionary Order) using two approaches: By using any sorting technique to sort array elements. By using sort() function present in Arrays class in util package in java.
If you don't want sort in place, and you would like to use guava, check out Ordering
.
Ordering.natural().sortedCopy(yourInputThatIsIterableAndHasStrings);
or:
Ordering.usingToString().sortedCopy(yourInputThatIsIterableThatYouWantToSortBasedOnToString);
If you want to sort in place, then you should just use Collections.sort(...)
.
Hope this helps.
String implements Comparable, and its natural order is the lexicographical order. All you have to do is
Collections.sort(s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With