【java】Collection判重,去重,查重

转载请注明出处:http://blog.csdn.net/u012250875/article/details/78195963

1.判重

判断集合中是否有重复元素,则可以利用java的Set集合,Set天生有不重复的buff,因此将入参通过HashSet的构造器转为Set,然后比较Set的size与原集合的size来判断是否含有重复元素。泛型注意重写equals和hashcode方法,实现代码如下:

    /**
     * @author puyf
     * @Description:判断Collection中的元素是否有重复元素
     * @param datas
     *            需要判断的目标集合
     * @return
     */
    public static boolean isRepeatInCollection(Collection<?> datas) {
        if (datas == null) {// 为空则认为不含重复元素
            return false;
        }
        if (datas instanceof Set) {//如果是set则不含有重复元素
            return false;
        }
        Set<?> noRepeatSet = new HashSet<>(datas);
        return !(datas.size() == noRepeatSet.size());
    }

2.去重

去重也是用到了Set无重复buff,直接使用Set实现类的构造方法来完成即可

    /**
     * @author puyf
     * @Description:Collection中去重并将集合转为List
     * @param datas
     * @return
     */
    public static <T> List<T> distinct(Collection<T> datas) {
        if(datas == null){
            return new ArrayList<>();
        }
        Set<T> set = new HashSet<>(datas);//使用HashSet构造方法去重
        return new ArrayList<>(set);
    }

3.查重

找出集合类(这里的集合类指List)中重复元素,查重主要是通过遍历来实现

    /**
     * @author puyf
     * @Description:找出list中的重复数据
     * @param datas
     * @return
     */
    public static <T> List<T> findRepeat(Collection<T> datas) {
        if (datas instanceof Set) {
            return new ArrayList<>();
        }
        HashSet<T> set = new HashSet<T>();
        List<T> repeatEles = new ArrayList<T>();
        for (T t : datas) {
            if (set.contains(t)) {
                repeatEles.add(t);
            } else {
                set.add(t);
            }
        }
        return repeatEles;
    }

4.使用

public static void main(String[] args) {
    List<Integer> data = new ArrayList<>(Arrays.asList(new Integer[] { 1, 2, 1 }));
    System.out.println("Collection{1,2,1}中是否含有重复元素:"+isRepeatInCollection(data));
    System.out.println("找出Collection{1,2,1}中的重复元素:"+findRepeat(data));
    System.out.println("Collection{1,2,1}去重的结果是"+distinct(data));
}

//执行结果:
Collection{1,2,1}中是否含有重复元素:true
找出Collection{1,2,1}中的重复元素:[1]
Collection{1,2,1}去重的结果是[1, 2]

更多集合操作(点击查看

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值