JAVA List和Map切割方法

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class CollectionUtil {

    /**
     * 将map切成段,作用与PHP的array_chunk函数相当
     *
     * @param chunkMap 被切段的map
     * @param chunkNum 每段的大小
     * @param       map的key类型
     * @param       map的value类型 如果是自定义类型,则必须实现equals和hashCode方法
     * @return
     */
    public static  List> mapChunk(Map chunkMap, int chunkNum) {
        if (chunkMap == null || chunkNum <= 0) {
            List> list = new ArrayList<>();
            list.add(chunkMap);
            return list;
        }
        Set keySet = chunkMap.keySet();
        Iterator iterator = keySet.iterator();
        int i = 1;
        List> total = new ArrayList<>();
        Map tem = new HashMap<>();
        while (iterator.hasNext()) {
            k next = iterator.next();
            tem.put(next, chunkMap.get(next));
            if (i == chunkNum) {
                total.add(tem);
                tem = new HashMap<>();
                i = 0;
            }
            i++;
        }
        if(!CollectionUtils.isEmpty(tem)){
            total.add(tem);
        }
        return total;
    }


    /**
     * 将list切割
     *
     * @param chunkList 被分隔的数组
     * @param chunkNum  每段的大小
     * @param        List中的类型
     * @return
     */
    public static  List> listChunk(List chunkList, int chunkNum) {
        if (chunkList == null || chunkNum <= 0) {
            List> t = new ArrayList<>();
            t.add(chunkList);
            return t;
        }
        Iterator iterator = chunkList.iterator();
        int i = 1;
        List> total = new ArrayList<>();
        List tem = new ArrayList<>();
        while (iterator.hasNext()) {
            T next = iterator.next();
            tem.add(next);
            if (i == chunkNum) {
                total.add(tem);
                tem = new ArrayList<>();
                i = 0;
            }
            i++;
        }
        if(!CollectionUtils.isEmpty(tem)){
            total.add(tem);
        }
        return total;
    }

}

 

你可能感兴趣的:(Java)