打赏

java 查询list中重复的数据

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() + "次");
//        }
    

 

posted @ 2020-05-08 10:52  张学涛  阅读(9161)  评论(0编辑  收藏  举报