面试题:其中涉及到了对容器、泛型、以及冒泡排序
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * 题目要求:1.按班级计算List<Student>中学生的数量 2.按班级将学生排序 * * @author huang * */ public class Student { private int id; private String name; private int classRate; public int getId() { return id; } public String getName() { return name; } public int getClassRate() { return classRate; } public Student(int id, String name, int classRate) { this.id = id; this.name = name; this.classRate = classRate; } /** * 按班级计算学生数量 * * @param students * @return */ public static Map<Integer, List<Student>> getStudentCountByClassRate( List<Student> students) { Map<Integer, List<Student>> map = new HashMap<Integer, List<Student>>(); if (students != null && students.size() > 0) { for (Student s : students) { List<Student> stus = null; if (map.containsKey(s.getClassRate())) { stus = map.get(s.getClassRate()); } else { stus = new ArrayList<Student>(); } stus.add(s); map.put(s.getClassRate(), stus); } } return map; } /** * 冒泡交换 * * @param x * @param y * @param array */ public static void convert(int x, int y, Integer[] array) { int temp = array[x]; array[x] = array[y]; array[y] = temp; } /** * 按classRate排序 * * @param students * @return */ public static List<Student> sortStudentByClassRate(List<Student> students) { Map<Integer, List<Student>> map = getStudentCountByClassRate(students); Set<Integer> keySet = map.keySet(); Integer[] array = keySet.toArray(new Integer[] {}); 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.length) { if (array[j] > array[j + 1]) { convert(j, j + 1, array); } // convert(j, j + 1, array); } } } } List<Student> stus = new ArrayList<Student>(); for (int i : array) { stus.addAll(map.get(i)); } return stus; } public static void main(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<Student> stus = new ArrayList<Student>(); 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<Integer, List<Student>> map = getStudentCountByClassRate(stus); Set<Integer> keySet = map.keySet(); for (int i : keySet) { System.out.println("班级" + i + "有学生" + ((List<Student>) map.get(i)).size()); } List<Student> sts = sortStudentByClassRate(stus); for (Student s : sts) { System.out.println("学生姓名:" + s.getName() + ",属于" + s.getClassRate() + "班"); } } }
测试结果:
班级1有学生4
班级2有学生2
班级3有学生3
学生姓名:a1,属于1班
学生姓名:a4,属于1班
学生姓名:a7,属于1班
学生姓名:a9,属于1班
学生姓名:a2,属于2班
学生姓名:a8,属于2班
学生姓名:a3,属于3班
学生姓名:a5,属于3班
学生姓名:a6,属于3班