1. 程式人生 > >集合排序工具類

集合排序工具類

package com.yufei.core.util;

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

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;

/**
  * <p>Title:SortUtil </p>
  * <p>Description: 排序類</p>
  * <p>Company:shentie </p> 
  * @author :lzw
  * @date   :2016年3月11日下午11:04:58
  * @version:V1.0.0
*/
public class SortUtil {
	public static void main(String[] args) {
		System.out.println(testMapSort());
	}
	
	/**
	 * 對list進行排序
	 * @param sortList 需要排序的list
	 * @param param1   排序的引數名稱
	 * @param orderType 排序型別:正序-asc;倒序-desc  
	 */
	public static List<?> sort(List<?> sortList, String param1, String orderType){
		Comparator<?> mycmp1 = ComparableComparator.getInstance ();
		if("desc".equals(orderType)){
			mycmp1 = ComparatorUtils. reversedComparator(mycmp1); //逆序(預設為正序)
		}
		
		ArrayList<Object> sortFields = new ArrayList<Object>();
		sortFields.add( new BeanComparator(param1 , mycmp1)); //主排序(第一排序)

		ComparatorChain multiSort = new ComparatorChain(sortFields);
		Collections.sort (sortList , multiSort);
		
		return sortList;
	}
	
	/**
	 * 對list進行排序
	 * @param sortList 需要排序的list
	 * @param param1   排序的引數名稱:引數長度
	 * @param param2   排序的引數名稱:排序引數
	 * @param orderType 排序型別:正序-asc;倒序-desc  
	 */
	public static List<Map> sortParam2(List<Map> sortList, String param1,String param2, String orderType){
		Comparator<?> mycmp1 = ComparableComparator.getInstance ();
		Comparator<?> mycmp2 = ComparableComparator.getInstance ();
		if("desc".equals(orderType)){
			mycmp1 = ComparatorUtils. reversedComparator(mycmp1); //逆序(預設為正序)
		}
		
		ArrayList<Object> sortFields = new ArrayList<Object>();
		sortFields.add( new BeanComparator(param1 , mycmp1)); //主排序(第一排序)
		sortFields.add( new BeanComparator(param2 , mycmp2)); //主排序(第一排序)

		ComparatorChain multiSort = new ComparatorChain(sortFields);
		Collections.sort (sortList , multiSort);
		
		return sortList;
	}
	
	public static List<Map> testMapSort(){
		List<?> sortList = new ArrayList<Object>();
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", "1");
		map.put("age", "1");
		
		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("name", "2");
		map2.put("age", "13");
		
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("name", "2");
		map1.put("age", "12");
		
		List<Map> list = new ArrayList<Map>();
		list.add(map);
		list.add(map1);
		list.add(map2);
		
		//return sort(list, "age", "asc");
		return sortParam2(list, "name", "age", "asc");
	}
	
}