共享关于List的几个常用方法

Posted on 2010-04-27 15:08 java小爬虫 阅读(3807) 评论(0)  编辑  收藏

// 把一个List平均分成二个List
 public static List[] splitList(List list) {
  ArrayList left = new ArrayList();
  ArrayList right = new ArrayList();
  ArrayList[] result = new ArrayList[2];
  if (null == list || list.size() == 0)
   return result;
  for (int i = 0; i < list.size(); i++) {
   if (i % 2 == 0) {
    left.add(list.get(i));
   }
   else {
    right.add(list.get(i));
   }
  }
  result[0] = left;
  result[1] = right;
  return result;
 }



 // 把一个List按照size的大小分组;
 public static List splitListByParameter(List list, int size) {
  if (null == list || list.size() == 0 || size == 0)
   return null;
  int arraySize = 0;
  if (list.size() % size == 0)
   arraySize = list.size() / size;
  else
   arraySize = list.size() / size + 1;

  List result = new ArrayList(arraySize);
  int temp = 0;
  while (temp < arraySize) {
   try {
    if (temp == arraySize - 1)
     result.add(list.subList(temp * size, list.size()));
    else
     result.add(list.subList(temp * size, temp * size + size));
   }
   catch (RuntimeException e) {
    e.printStackTrace();
   }
   temp++;
  }
  return result;
 }




/**
  * 从一个LIST中随机获取size条记录,返回值LIST;
  *
  */
 public static List getRandomRecords(List list , int size) {
  if(list==null||list.size()<=size) return list ;
  List result = new ArrayList();
  Random random = new Random();
  while(result.size()<size){
  Object obj = list.get(random.nextInt(list.size()));
  if(!result.contains(obj)){
  result.add(obj);
  }
  }
  return result ;
 }

只有注册用户登录后才能发表评论。


网站导航: