有一个List<CommonDictionary>,
CommonDictionary的结构:
- /**
- * 主键id
- */
- private Long id;
- /**
- * 组id
- */
- private String groupId;
- /**
- * 键<br />不能取值为key,因为key是关键字
- */
- private String key2;
- /**
- * 值
- */
- private String value;
- /**
- * 描述
- */
- private String description;
我需要对key2进行排序.
说明:
(1)key2的值是唯一的,不重复;
(2)key2的所有取值都已知.
按照什么方式排序呢?
- "company_n","product_stand","production_no","registration_c","production_addr","company_web"
排序前:
13company_name武汉市
17company_website公司网址
14product_standard产品标准aa
18production_address生产地址
15production_no生产证号
16registration_certificate_number注册证号drfdf
---------------------------------
排序后:
13company_name武汉市
14product_standard产品标准aa
15production_no生产证号
16registration_certificate_number注册证号drfdf
18production_address生产地址
17company_website公司网址
测试方法如下:
- @Test
- public void tst_77(){
- List<CommonDictionary> list=DictionaryParam.getList(Constant2.DICTIONARY_GROUP_ANTICOUNTERFEIT_CODE);
- String orderTitles[]=new String[]{"company_n","product_stand","production_no","registration_c","production_addr","company_web"};
- for(int i=0;i<list.size();i++){
- CommonDictionary commonDictionary33=list.get(i);
- System.out.println(commonDictionary33.getId()+"\t"+commonDictionary33.getKey2()+"\t"+commonDictionary33.getValue());
- }
- Collections.sort(list,new SystemHWUtil. ArrayListComparator(orderTitles,"Key2"));
- System.out.println("---------------------------------");
- for(int i=0;i<list.size();i++){
- CommonDictionary commonDictionary33=list.get(i);
- System.out.println(commonDictionary33.getId()+"\t"+commonDictionary33.getKey2()+"\t"+commonDictionary33.getValue());
- }
- }
执行结果:
SystemHWUtil. ArrayListComparator 实现如下:
- public static class ArrayListComparator implements Comparator{
- /***
- * 排序的依据
- */
- private String titles[];
- /***
- * 对哪个列进行排序
- */
- private String comparedProperty;
- public ArrayListComparator(String[] titles,String comparedProperty) {
- super();
- this.titles = titles;
- this.comparedProperty=comparedProperty;
- }
- public int compare(Object o1, Object o2) {
- if(null!=o1&&null!=o2)
- {
- try {
- if(SystemHWUtil.indexOfArr(titles,(String)ReflectHWUtils.getObjectValue(o1, comparedProperty) ) >
- SystemHWUtil.indexOfArr(titles,(String)ReflectHWUtils.getObjectValue(o2, comparedProperty))){
- return 1/*大于*/;
- }else {
- return -1/*小于*/;
- }
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- return 0/*等于*/;
- }
- }
SystemHWUtil.indexOfArr 参考http://hw1287789687.iteye.com/blog/2145187
注意:
(1)titles中的元素不要有重复;
(2)ArrayListComparator 可应用于所有的Object,应该它没有与具体的类关联,而是通过反射来获取成员变量的值.
关于反射,可以参阅:http://hw1287789687.iteye.com/blog/2124280
遗留问题:
如何高效率地过滤String[]:{1,2,3,2}-->{1,2,3};