利用apache commons对List元素的多个属性进行排序
程序员文章站
2022-04-17 11:25:41
...
package com; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.beanutils.BeanComparator; import com.CfgModel; public class ListSorter { /** * List 元素的多个属性进行排序。例如 ListSorter.sort(list, "orderIndex", "treeLevel"),则先按 * orderIndex 属性排序,orderIndex 相同的元素按 treeLevel 属性排序。 * * @param list 包含要排序元素的 List * @param properties 要排序的属性。前面的值优先级高。 */ public static <V> void sort(List<V> list, final String... properties) { Collections.sort(list, new Comparator<V>() { public int compare(V o1, V o2) { if (o1 == null && o2 == null) return 0; if (o1 == null) return -1; if (o2 == null) return 1; for (String property : properties) { Comparator c = new BeanComparator(property); int result = c.compare(o1, o2); if (result != 0) { return result; } } return 0; } }); } public static void main(String[] args){ List<CfgModel> list = new ArrayList<CfgModel>(); CfgModel cfgModel1 = new CfgModel(); cfgModel1.setModelName("l1"); cfgModel1.setOrderIndex(1); cfgModel1.setTreeLevel(1); list.add(cfgModel1); CfgModel cfgModel2 = new CfgModel(); cfgModel2.setModelName("l12"); cfgModel2.setOrderIndex(2); cfgModel2.setTreeLevel(1); list.add(cfgModel2); CfgModel cfgModel3 = new CfgModel(); cfgModel3.setModelName("l2"); cfgModel3.setOrderIndex(1); cfgModel3.setTreeLevel(2); list.add(cfgModel3); CfgModel cfgModel4 = new CfgModel(); cfgModel4.setModelName("l21"); cfgModel4.setOrderIndex(2); cfgModel4.setTreeLevel(2); list.add(cfgModel4); sort(list, "orderIndex","treeLevel"); for (CfgModel c:list){ System.out.println(c.getModelName()+","+c.getOrderIndex()+","+c.getTreeLevel()); } } }
结果:
l1,1,1
l2,1,2
l12,2,1
l21,2,2
先按orderIndex排序然后按treeLevel排序
上一篇: 用核心-路径法设计页面_html/css_WEB-ITnose
下一篇: 队列有几种实现方式?