Lexicographic ordering of a list of strings using guava

What is an easy way to do lexicographic ordering of a list of strings using guava. I do it like this:

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); 
+7
source share
3 answers

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

 Collections.sort(s); 
+7
source

If you don't need in-place sorting and would like to use guava, check out Ordering .

 Ordering.natural().sortedCopy(yourInputThatIsIterableAndHasStrings); 

or

 Ordering.usingToString().sortedCopy(yourInputThatIsIterableThatYouWantToSortBasedOnToString); 

If you want to sort in place, you should just use Collections.sort(...) .

Hope this helps.

+8
source

Put it simply (since String implements Comparable ):

 List<String> s = ... Collections.sort(s); 
+1
source

All Articles