package test.transsion; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; public class GroupByUserDemo { class User{ int age;//年龄 String name;//姓名 String grades;//班级 public User(){ } public User(int age,String name,String grades){ this.age=age; this.name=name; this.grades=grades; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGrades() { return grades; } public void setGrades(String grades) { this.grades = grades; } @Override public String toString() { return "User [age=" + age + ", name=" + name + ", grades=" + grades + "]"; } } /** * @param datas 集合对象 或list,set,map等 * @param c 比较器 * @return */ public static <T> List<List<T>> groupOrdering(Collection<T> datas,Comparator<? super T> c){ List<List<T>> list=new ArrayList<List<T>>(); for (T t : datas) { boolean issameGroup=false; for(int j=0;j<list.size();j++){ if(c.compare( t, list.get(j).get(0) )==0){ issameGroup=true; list.get(j).add(t); break; } } if(! issameGroup){ //新建分组集合的集合 List<T> listT=new ArrayList<T>(); list.add(listT); listT.add(t); } } return list; } public static void main(String[] args) { GroupByUserDemo sud=new GroupByUserDemo(); User u1=sud.new User(13,"cqs","一年级"); User u2=sud.new User(12,"jition","二年级"); User u3=sud.new User(14,"Jition","一年级"); User u4=sud.new User(15,"allen","二年级"); User u5=sud.new User(10,"hong","一年级"); User u6=sud.new User(11,"jaction","三年级"); List<User> list= new ArrayList<User>(); list.add(u1); list.add(u2); list.add(u3); list.add(u4); list.add(u5); list.add(u6); /** * 分组【多组多条数据】 */ List<List<User>> listUser=groupOrdering(list,new Comparator<User>(){ @Override public int compare(User o1, User o2) { return o1.getGrades().compareTo(o2.getGrades()); } }); System.out.println(listUser); } }
List集合分组
原创
©著作权归作者所有:来自51CTO博客作者cqs_jition的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:js中startsWith 函数不能在任何浏览器兼容的问题
下一篇:SQL面试题
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
JAVA list基础操作
list基本操作
System List Test