We would like to know how to sort a list of words by length then by alphabetical order.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; //from w ww .ja v a2 s. co m public class Main { public static void main(String[] args) { List<String> list=new ArrayList<>(); list.add("acowa"); list.add("cow"); list.add("aow"); Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length()>o2.length()){ return 1; }else{ return o1.compareTo(o2); } } }); System.out.println(list); } }
The code above generates the following result.