根据关键字对集合进行排序然后在按照拼音排序

package com.common.util;

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

import com.common.util.StringHelper;
/**
 * 2011-03-18
 * 对一个集合进行排序,首先按照关键字的出现顺序排序,然后在按照拼音排序
 * @author Bing
 *
 */
public class KeyWordComparator {
	Comparator<SearchResultVo> c=null;
	public KeyWordComparator(Comparator<SearchResultVo> c)
	{
		this.c=c;
	}
         public List<SearchResultVo> compare(List<SearchResultVo> vos,String key,int k) {
		List<SearchResultVo> temp=new ArrayList<SearchResultVo>();
		String key_pinyin=StringHelper.getPinyin(key).toLowerCase();
		int keylength=key_pinyin.length();
		List<SearchResultVo> result=new ArrayList<SearchResultVo>();
		boolean existkey=false;
		boolean leftstrexistkey=false;
		for(int i=vos.size()-1;i>=0;i--)
		{
			SearchResultVo vo=vos.get(i);
			String fullname=StringHelper.getPinyin(vo.getFullname()).toLowerCase();
			if(k+keylength<=fullname.length())
			{
				String name=fullname.substring(k, k+keylength);
				if(key_pinyin.equals(name))
				{
					existkey=true;
					temp.add(vo);
					vos.remove(i);
				}
				String leftstr=fullname.substring(k+1, fullname.length());
				if(leftstr.toLowerCase().indexOf(key_pinyin) != -1)
				{
					leftstrexistkey=true;
				}
			}
		}
		Collections.sort(temp, c);
		result.addAll(temp);
		if((existkey==false) && (leftstrexistkey==false))
		{
			result.addAll(vos);
			return result;
		}
		k=k+1;
		result.addAll(compare(vos,key,k));
		return result;
	}
}


测试方法:
                  SearchResultVo v1=new SearchResultVo();
		SearchResultVo v2=new SearchResultVo();
		SearchResultVo v3=new SearchResultVo();
		SearchResultVo v4=new SearchResultVo();
		SearchResultVo v5=new SearchResultVo();
		SearchResultVo v6=new SearchResultVo();
		SearchResultVo v7=new SearchResultVo();
		SearchResultVo v8=new SearchResultVo();
		SearchResultVo v9=new SearchResultVo();
		v1.setFullname("刘冰");
		v2.setFullname("刘伟");
		v3.setFullname("冰刘");
		v4.setFullname("刘建");
		v5.setFullname("冰刘e");
		v6.setFullname("冰刘a");
		v7.setFullname("刘志鹏");
		v8.setFullname("冰刘");
		v9.setFullname("冰的刘");
		
//		v1.setFullname("张凤连");
//		v2.setFullname("张月");
//		v3.setFullname("张大雷");
//		v4.setFullname("张月");
//		v5.setFullname("张楠");
//		v6.setFullname("张棋");
		List<SearchResultVo> list=new ArrayList<SearchResultVo>();
		list.add(v1);list.add(v2);list.add(v3);list.add(v4);list.add(v5);list.add(v6);list.add(v7);list.add(v8);list.add(v9);
		KeyWordComparator k=new KeyWordComparator(new SimpleSearchComparator());
		
		list=k.compare(list, "刘", 0);
                  //list=k.compare(list, "liu", 0);
		for(int i=0;i<list.size();i++)
		{
			System.out.println(list.get(i).getFullname());
		}

结果:
刘冰
刘建
刘伟
刘志鹏
冰刘
冰刘
冰刘a
冰刘e
冰的刘

你可能感兴趣的:(java,C++,c,C#,bing)