打赏

Collections练习之按照字符串长度进行排序

 

  不多说,直接上干货!

 

 

代码需求

   想从

[abcde, cba, aa, zzz, cba, nbaa]

 

  变成

[aa, cba, cba, zzz, nbaa, 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");
        System.out.println(list);
        
        //对list集合进行指定顺序的排序。
        Collections.sort(list);
        mySort(list);
        mySort(list,new ComparatorByLength());
        Collections.sort(list,new ComparatorByLength());
        System.out.println(list);
    }
    
    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);
                }
            }
        }
    }
}

 

 

 

 

 

ComparatorByLength.java

package zhouls.bigdata.DataFeatureSelection.test;

import java.util.Comparator;

public class ComparatorByLength implements Comparator<String> {
    public int compare(String o1, String o2) {
        int temp = o1.length() - o2.length();
        return temp==0?o1.compareTo(o2): temp;
    }
}

 

posted @ 2017-09-22 20:09  大数据和AI躺过的坑  阅读(884)  评论(0编辑  收藏  举报