// Simple program that demonstrates sorting a list twice and seeing if the // second sort preserves the order of the first for values that are considered // equal. import java.util.*; public class StableSort { public static void main(String[] args) { // construct the list and sort it alphabetically String[] words = {"four", "score", "and", "seven", "years", "ago", "our", "fathers", "brought", "forth", "on", "this", "continent", "a", "new", "nation", "conceived", "in", "liberty", "and", "dedicated", "to", "the", "proposition", "that", "all", "men", "are", "created", "equal"}; System.out.println("before simple sort = " + Arrays.toString(words)); Arrays.sort(words); System.out.println("after simple sort = " + Arrays.toString(words)); // now sort a second time by sorting on string length (shorter strings // coming before longer strings)...the big question is whether words of // a given length will appear in alphabetical order (meaning that the // relative order from the previous sort was preserved) Arrays.sort(words, (a, b) -> a.length() - b.length()); System.out.println("after length sort = " + Arrays.toString(words)); // The second call on Arrays.sort uses a Java 8 feature known as a // lambda. The following is a second equivalent version that uses // different Java 8 features. // Arrays.sort(words, Comparator.comparingInt(String::length)); } }