JAVA List and Map Cutting Tools

  • 2021-08-16 23:54:56
  • OfStack

Students who use PHP know that array_chunk function is used to cut and segment data, but there is no suitable function to segment List and Map in java.

Here I wrote a cutting tool and shared it under 1


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;
/**
 * @author lanfangyi
 * @version 1.0
 * @since 2019/2/28 20:39
 */
public class CollectionUtil {
  private CollectionUtil(){
  }
  /**
   *  Will map Cut into sections, the function is the same as that of PHP Adj. array_chunk Functional equivalence 
   *
   * @param chunkMap  Segmented map
   * @param chunkNum  Size of each segment 
   * @param <k>   map Adj. key Type 
   * @param <v>   map Adj. value Type   If it is a custom type, you must implement the equals And hashCode Method 
   * @return
   */
  public static <k, v> List<Map<k, v>> mapChunk(Map<k, v> chunkMap, int chunkNum) {
    if (chunkMap == null || chunkNum <= 0) {
      List<Map<k, v>> list = new ArrayList<>();
      list.add(chunkMap);
      return list;
    }
    Set<k> keySet = chunkMap.keySet();
    Iterator<k> iterator = keySet.iterator();
    int i = 1;
    List<Map<k, v>> total = new ArrayList<>();
    Map<k, v> 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;
  }
  /**
   *  Will list Cutting 
   *
   * @param chunkList  Separated array 
   * @param chunkNum  Size of each segment 
   * @param <T>    List Type in 
   * @return
   */
  public static <T> List<List<T>> listChunk(List<T> chunkList, int chunkNum) {
    if (chunkList == null || chunkNum <= 0) {
      List<List<T>> t = new ArrayList<>();
      t.add(chunkList);
      return t;
    }
    Iterator<T> iterator = chunkList.iterator();
    int i = 1;
    List<List<T>> total = new ArrayList<>();
    List<T> 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;
  }
}

Supplement: List set in java stores Map

The list collection holds the Map example:


List<Map<String,Object>> listMap = new ArrayList<>();
Map<String,Object> map = new HashMap<String,Object>();
List<Entity> list = new ArrayList<>();
map.put("list",list);
listMap.add(map);

Related articles: