集合相关的一些方法

1、含有null值的集合获取最大值

     * 扩展 Collections 中获得list 中最大值的方法过滤掉为null的值
     *
     * @param coll 参数 list
     * @param <T> 参数类型
     * @return
     */
    public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
        if (coll != null && !coll.isEmpty()) {
            Iterator<? extends T> i = coll.iterator();
            T candidate = null;
            while (candidate == null && i.hasNext()) {
                candidate = i.next();
            }
            while (i.hasNext()) {
                T next = null;
                while (next == null && i.hasNext()) {
                    next = i.next();
                }
                if (next != null && next.compareTo(candidate) > 0) {
                    candidate = next;
                }
            }
            return candidate;
        }
        throw new RuntimeException("Collection is null");
    }

2、快速筛选出大集合中不包含小集合的数据集合

     * 快速选出source 中 不包含 destination 的 List
     * @param source 大的集合
     * @param destination 小的集合
     * @return
     */
    private static List<String> removeAll(List<String> source, List<String> destination) {
        List<String> result = new LinkedList<>();
        Set<String> destinationSet = new HashSet<>(destination);
        for(String t : source) {
            if (!destinationSet.contains(t)) {
                result.add(t);
            }
        }
        return result;
    }

3、获得概率随机值

    /**
     * 随机圆桌算法
     *
     * @param weightList 权重列表
     * @return 权重数组的下标
     */
    public static int randomTableNew(List<Integer> weightList) {
        int target = 0;
        int total = weightList.stream().reduce((integer, integer2) -> integer + integer2).get();
        SecureRandom random = null;
        try {
            random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage());
        }
        int randInt = random.nextInt(total);
        randInt += 1;
        for (int i = 0; i < weightList.size(); i++) {
            int length = weightList.get(i);
            target += length;
            if (randInt <= target) {
                return i;
            }
        }
        return 0;
    }

快速生成相同元素指定长度的集合

Collections.nCopies((int)l, "")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值