1. 程式人生 > >java程式碼將一個數組分為多個等長度的陣列

java程式碼將一個數組分為多個等長度的陣列

首先這個是為了實現一次請求的資料量不會由於返回的資料量過大導致記憶體溢位,所以分批獲取

 

@SuppressWarnings("unused")
	public static List<String> getList(int targ,List<String> mList) {
		List<String> idsStrList = new ArrayList<String>();
      List<List<String>>mEndList=new ArrayList<>();
//      System.out.println(mList.toString());
      if( mList.size()%targ!=0) {
          for (int j = 0; j < mList.size() / targ + 1; j++) {
              if ((j * targ + targ) < mList.size()) {
                  mEndList.add(mList.subList(j * targ, j * targ + targ));//0-3,4-7,8-11    j=0,j+3=3   j=j*3+1
              } else if ((j * targ + targ) > mList.size()) {
                  mEndList.add(mList.subList(j * targ, mList.size()));
              } else if (mList.size() < targ) {
                  mEndList.add(mList.subList(0, mList.size()));
              }
          }
      }else if(mList.size()%targ==0){
          for (int j = 0; j < mList.size() / targ; j++) {
              if ((j * targ + targ) <= mList.size()) {
                  mEndList.add(mList.subList(j * targ, j * targ + targ));//0-3,4-7,8-11    j=0,j+3=3   j=j*3+1
              } else if ((j * targ+ targ) > mList.size()) {
                  mEndList.add(mList.subList(j * targ, mList.size()));
              } else if (mList.size() < targ) {
                  mEndList.add(mList.subList(0, mList.size()));
              }
          }
      }
//      for (int i = 0; i < mEndList.size(); i++) {
//          log.info(mEndList.get(i).toString()+"");
//      }
      for (List<String> list : mEndList) {
    	  String idsStr = "";
    	  for (String string : list) {
    		  idsStr = idsStr + string + ",";
		}
    	  idsStrList.add(idsStr);
	}
      return idsStrList;
  }	
	public static void main(String[] args) {
		List<String> strList = new ArrayList<String>();
		for (int i = 0; i < 1000000; i++) {
			strList.add("ids"+i);
		}
		long startTime = System.currentTimeMillis();
		System.out.println(startTime);
		List<String> list = getList(20,strList);
		long endTime = System.currentTimeMillis();
		System.out.println("第一個20個任務:"+list.get(0));
		System.out.println("總共耗時:"+(endTime - startTime) );
	}