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
pub开发者_开发问答lic 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);
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);
Put simply (since String
implements Comparable
):
List<String> s = ...
Collections.sort(s);
精彩评论