代码需求
由
[aa, abcde, cba, cba, nbaa, zzz]
变成
max=abcde
CollectionsDemo.java
package zhouls.bigdata.DataFeatureSelection.test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.TreeSet; import zhouls.bigdata.DataFeatureSelection.test.ComparatorByLength; public class CollectionsDemo { /** * @param args */ public static void main(String[] args) { /* * Collections:是集合框架的工具类。 * 里面的方法都是静态的。 */ demo(); } public static void demo(){ List<String> list = new ArrayList<String>(); list.add("abcde"); list.add("cba"); list.add("aa"); list.add("zzz"); list.add("cba"); list.add("nbaa"); Collections.sort(list); System.out.println(list); //获取最大值。 String max = Collections.max(list,new ComparatorByLength()); System.out.println("max="+max); } public static <T> void mySort(List<T> list,Comparator<? super T> comp){ for (int i = 0; i < list.size()-1; i++) { for (int j = i+1; j < list.size(); j++) { if(comp.compare(list.get(i), list.get(j))>0){ T temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); Collections.swap(list, i, j); } } } } public static <T extends Comparable<? super T>> void mySort(List<T> list){ for (int i = 0; i < list.size()-1; i++) { for (int j = i+1; j < list.size(); j++) { if(list.get(i).compareTo(list.get(j))>0){ T temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); Collections.swap(list, i, j); } } } } }
本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/7576980.html,如需转载请自行联系原作者