温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何实现Java List不重复抽取Util

发布时间:2021-10-12 09:47:29 来源:亿速云 阅读:227 作者:iii 栏目:编程语言

本篇内容主要讲解“如何实现Java List不重复抽取Util”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何实现Java List不重复抽取Util”吧!

import java.util.ArrayList;import java.util.List;import java.util.Random;/** * @Author: wuyiqi * @Date: 2021-03-16 10:17 * @Description: 万能list抽取不重复 */public class ExtractUtil
{   /**    * 批量抽取    * @param size 抽取数量    * @param records 抽取的列表    * @param <T> 类型    * @return    */   public static <T> List<T> extractList(int size, List<T> records)
   {      int total = records.size();      if (total < 1 || size < 1)
      {         return null;
      }      if (size >= total)
      {         return records;
      }      // 如果抽取的百分比大于50%,那就抽取不需要的,再反转      boolean reverse = false;      if ((double) size / total > 0.5)
      {
         reverse = true;
         size = total - size;
      }      // 抽取核心方法      List<T> list = new ArrayList<>();      for (int i = 0; i < size; i++)
      {         int random = new Random().nextInt(total);         T t = extract(random, list, records);         if (null != t)
         {
            list.add(t);
         }
      }      // 如果反转      if (reverse)
      {
         List<T> temp = new ArrayList<>();         for (T record : records)
         {if (!list.contains(record))
            {
               temp.add(record);
            }
         }
         list = temp;
      }      return list;
   }   /**    * 单个抽取;不重复抽取    * @param index 抽取位置    * @param newList 抽中的列表    * @param records 抽取的列表    * @param <T> 类型    * @return    */   public static <T> T extract(int index, List<T> newList, List<T> records)
   {      int total = records.size();      if (total < 1 || index >= total)
      {         return null;
      }      T t = records.get(index);      if (newList.contains(t))
      {
         t = extract(new Random().nextInt(total), newList, records);
      }      return t;
   }
}

到此,相信大家对“如何实现Java List不重复抽取Util”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI