Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lexicographical ordering of string list using guava

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);
like image 373
gautamr Avatar asked Feb 03 '11 11:02

gautamr


People also ask

How do I sort a list of strings Lexicographically?

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.

What is lexicographical order example?

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.

How do you sort an Arraylist of string Lexicographically?

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.


2 Answers

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.

like image 122
Tom Avatar answered Sep 17 '22 18:09

Tom


String implements Comparable, and its natural order is the lexicographical order. All you have to do is

Collections.sort(s);
like image 24
JB Nizet Avatar answered Sep 20 '22 18:09

JB Nizet