importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.Set;/*** 题目要求:1.按班级计算List中学生的数量 2.按班级将学生排序
*
*@authorhuang
**/
public classStudent {private intid;privateString name;private intclassRate;public intgetId() {returnid;
}publicString getName() {returnname;
}public intgetClassRate() {returnclassRate;
}public Student(int id, String name, intclassRate) {this.id =id;this.name =name;this.classRate =classRate;
}/*** 按班级计算学生数量
*
*@paramstudents
*@return
*/
public static Map>getStudentCountByClassRate(
Liststudents) {
Map> map = new HashMap>();if (students != null && students.size() > 0) {for(Student s : students) {
List stus = null;if(map.containsKey(s.getClassRate())) {
stus=map.get(s.getClassRate());
}else{
stus= new ArrayList();
}
stus.add(s);
map.put(s.getClassRate(), stus);
}
}returnmap;
}/*** 冒泡交换
*
*@paramx
*@paramy
*@paramarray*/
public static void convert(int x, inty, Integer[] array) {int temp =array[x];
array[x]=array[y];
array[y]=temp;
}/*** 按classRate排序
*
*@paramstudents
*@return
*/
public static List sortStudentByClassRate(Liststudents) {
Map> map =getStudentCountByClassRate(students);
Set keySet =map.keySet();
Integer[] array= keySet.toArray(newInteger[] {});if (array != null && array.length > 0) {for (int i = 0; i < array.length; i++) {for (int j = 0; j < array.length; j++) {if (j + 1 array[j + 1]) {
convert(j, j+ 1, array);
}//convert(j, j + 1, array);
}
}
}
}
List stus = new ArrayList();for (inti : array) {
stus.addAll(map.get(i));
}returnstus;
}public static voidmain(String[] args) {
Student s1= new Student(1, "a1", 1);
Student s2= new Student(2, "a2", 2);
Student s3= new Student(3, "a3", 3);
Student s4= new Student(4, "a4", 1);
Student s5= new Student(5, "a5", 3);
Student s6= new Student(6, "a6", 3);
Student s7= new Student(7, "a7", 1);
Student s8= new Student(8, "a8", 2);
Student s9= new Student(9, "a9", 1);
List stus = new ArrayList();
stus.add(s1);
stus.add(s2);
stus.add(s3);
stus.add(s4);
stus.add(s5);
stus.add(s6);
stus.add(s7);
stus.add(s8);
stus.add(s9);
Map> map =getStudentCountByClassRate(stus);
Set keySet =map.keySet();for (inti : keySet) {
System.out.println("班级" + i + "有学生"
+ ((List) map.get(i)).size());
}
List sts =sortStudentByClassRate(stus);for(Student s : sts) {
System.out.println("学生姓名:" + s.getName() + ",属于" +s.getClassRate()+ "班");
}
}
}