算法问题:关于list里重复值的处理

图片说明

循环过程中,以每个当前循环的值为key,如果存在map中,就加入列表,不存在就新建一个存入map.Java的参考代码:

 public static void main(String[] args){
        List<Integer> values =  new ArrayList<Integer>();
        int [] array = {5,2,6,5,2,1,5,4,2,6,2,4,1};
        for(int i:array){
            values.add(i);
        }

        Map<String,List<Integer>> result = new HashMap<String,List<Integer>>();
        for(Integer value:values){
            if(result.containsKey(value+"")){
                result.get(value+"").add(value);//存在加入对应的列表中
            }else{//不存在,新建一个加入map中
                List<Integer> list = new ArrayList<Integer>();
                list.add(value);
                result.put(value+"", list);
            }
        }

        //处理完成,打印结果
        for(Entry<String, List<Integer>> entry:result.entrySet()){
            System.out.println(entry.getKey()+",values:"+entry.getValue());
        }

可以一步到位,直接遍历list,每个元素作为map的key,同时加到map的value对应的list中。
这样就生成了map,然后遍历map,把value的list元素只有一个的key,value删除