List集合分组
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;}@Overridepublic?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>(){@Overridepublic?int?compare(User?o1,?User?o2)?{return?o1.getGrades().compareTo(o2.getGrades());}});System.out.println(listUser);}}
轉載于:https://blog.51cto.com/1929297/2055564
總結
- 上一篇: 年轻的程序员怎么快速成为架构师?
- 下一篇: python paramiko使用