开发者

lexicographical ordering of string list using guava

开发者 https://www.devze.com 2023-02-08 02:34 出处:网络
what is the simple way to do lexicographical ordering of string list using guava. I do it this way: List<String> s = newArrayList(

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消