java-排序

代码

package createCode;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("create code");
		ListSortTest lt = new ListSortTest();
		lt.main();
		
	}
}
package createCode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListSortTest {
    public void main(){
	System.out.println("- 字符排序 ----------");
	sortString();
	System.out.println("- map排序 ----------");
	sortMap();
    }
    private void sortString(){
	List list = new ArrayList();
	for(int i=0;i<10;i++){
	    int shu = i;
	    if(i%2==0){
		shu = shu+1;
	    }else{
		shu = shu-1;
	    }
	    list.add(String.valueOf(shu));
	}
	System.out.println(list.toString());
	list.sort(new Comparator(){
	    public int compare(String o1,String o2){
		return o1.compareTo(o2);
	    }
	});
	System.out.println(list.toString());
    }
    private void sortMap(){
	List> list = new ArrayList>();
	for(int i=0;i<10;i++){
	    int shu = i;
	    if(i%2==0){
		shu = shu+1;
	    }else{
		shu = shu-1;
	    }
	    Map map = new HashMap();
	    map.put("objid", String.valueOf(shu));
	    list.add(map);
	}
	System.out.println(list.toString());
	list.sort(new Comparator>(){
	    public int compare(Map o1,Map o2){
		return o1.get("objid").toString().compareTo(o2.get("objid").toString());
	    }
	});
	System.out.println(list.toString());
    }
}

运行效果

java-排序_第1张图片

你可能感兴趣的:(java)