List<Student> testList = new ArrayList<Student>(); List<Student> repeatList = new ArrayList<Student>();//用於存放重復的元素的list Map<String, Integer> map = new HashMap<>(); for(Student s : testList){ //1:map.containsKey() 檢測key是否重復 if(map.containsKey(s.getStuName())){ repeatList.add(s);//獲取重復的學生名稱 Integer num = map.get(s.getStuName()); map.put(s.getStuName(), num+1); }else{ map.put(s.getStuName(), 1); } //2: 這個key是不是存在對應的value(key是否在map中) // Integer count = map.get(s.getStuName());//這種寫法也可以,異曲同工 // if (count == null) { // map.put(s.getStuName(), 1); // } else { // map.put(s.getStuName(), (count + 1)); // } } // for(Student s : repeatList){ // System.out.println("相同的元素:" + s.getStuName()); // } // for(Map.Entry<String, Integer> entry : map.entrySet()){ // System.out.println("學生:" + entry.getKey() + "的名字出現了:" + entry.getValue() + "次"); // }