Created
April 20, 2016 15:58
-
-
Save mtorchiano/3372b5482fcb407c749d514fe7029783 to your computer and use it in GitHub Desktop.
Sorting evolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Comparator; | |
import static java.util.Comparator.*; | |
/** | |
* How sorting an array of strings by descending length | |
* evolved with the introduction of new Java technologies. | |
*/ | |
public class SortingEvolution { | |
public static void main(String[] args) { | |
String words[] = "Any text you like to process in this program" | |
.split(" +"); | |
// Java 2 | |
Arrays.sort(words,new Comparator(){ | |
public int compare(Object o1, Object o2) { | |
return ((String)o2).length()-((String)o1).length(); | |
} | |
}); | |
for(String w:words) System.out.print(w+", "); | |
System.out.println(); | |
// Java 5+, Generics | |
Arrays.sort(words,new Comparator<String>(){ | |
public int compare(String s1, String s2) { | |
return s2.length()-s1.length(); | |
} | |
}); | |
for(String w:words) System.out.print(w+", "); | |
System.out.println(); | |
// Java 8+, Lambda expression | |
Arrays.sort(words,(s1,s2)->s2.length()-s1.length()); | |
for(String w:words) System.out.print(w+", "); | |
System.out.println(); | |
// Java 8+, Factory methods + method reference + boxing | |
Arrays.sort(words,comparing(String::length).reversed()); | |
for(String w:words) System.out.print(w+", "); | |
System.out.println(); | |
// Java 8+, Factory methods + method reference + primitives | |
Arrays.sort(words,comparingInt(String::length).reversed()); | |
for(String w:words) System.out.print(w+", "); | |
System.out.println(); | |
// Java 8+, streams | |
Arrays.stream(words) | |
.sorted(comparingInt(String::length).reversed()) | |
.forEach(w -> System.out.print(w+", ")); | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment