001package top.cenze.utils; 002 003import cn.hutool.core.convert.Convert; 004import cn.hutool.core.util.ObjectUtil; 005import cn.hutool.core.util.StrUtil; 006import com.alibaba.fastjson.JSON; 007import lombok.extern.slf4j.Slf4j; 008 009import java.util.*; 010import java.util.stream.Collectors; 011 012/** 013 * @desc: 集合工具 014 * @author: chengze 015 * @createByDate: 2024/1/12 9:21 016 */ 017@Slf4j 018public class CollectionUtil { 019 020 /** 021 * 查一个字符串集合内的字符串是否包含某一个str(忽略字符串中的大小写) 022 * @param str 023 * @param lstStr 024 * @return 返回集合中第一个包含此str的字符串 025 */ 026 public static String containsStrIgnoreCase(String str, List<String> lstStr) { 027 if (cn.hutool.core.collection.CollectionUtil.isEmpty(lstStr)) { 028 return null; 029 } 030 031 // lsit 转 set 032 Set<String> setkeys = lstStr.stream().collect(Collectors.toSet()); 033 log.info("containsStrIgnoreCase keys: {}", JSON.toJSONString(setkeys)); 034 035 // 接口关键字集合为空时,则赋一个空值 036 String[] keys = null; 037 if (cn.hutool.core.collection.CollectionUtil.isEmpty(setkeys)) { 038 setkeys = new HashSet<>(); 039 setkeys.add(""); 040 keys = new String[] {""}; 041 } else { 042 keys = Convert.toStrArray(setkeys); 043 } 044 045 // 查一个字符串集合内的字符串是否包含某一个str,返回集合中第一个包含此str的字符串 046 return StrUtil.getContainsStrIgnoreCase(str, keys); 047 } 048 049 /** 050 * List集合切割成几份 051 * https://blog.csdn.net/qq_43532275/article/details/123786761 052 * @param lstObject 053 * @param parts 几份,如果为空(默认1份) 054 * @param <T> 055 * @return 返回map的key从0开始 056 */ 057 public static <T> Map<Integer, List<T>> slice(List<T> lstObject , Integer parts) { 058 if (ObjectUtil.isNull(parts)) { 059 parts = 1; 060 } 061 062 // 切割后的map 063 Map<Integer, List<T>> mapSlice = new HashMap<>(); 064 065 // 如果只分1份,直接返回 066 if (parts.equals(1)) { 067 mapSlice.put(0, lstObject); 068 return mapSlice; 069 } 070 071 int groupCount = lstObject.size() / parts; // 计算商 072 int residue = lstObject.size() % parts; // 计算余数 073 log.info("slice groupCount: {}, residue: {}", groupCount, residue); 074 075 for (int i = 0; i < parts; i++) { 076 // 把数据拆成N小组 077 int startIndex = i * groupCount; 078 int endIndex = startIndex + groupCount; 079 if (i == parts - 1) { 080 endIndex = endIndex + residue; 081 } 082 if (endIndex > lstObject.size()) { 083 endIndex = lstObject.size(); 084 } 085 log.info("slice startIndex: {}, endIndex: {}", startIndex, endIndex); 086 List<T> sublist = lstObject.subList(startIndex, endIndex); 087 088 if (cn.hutool.core.collection.CollectionUtil.isNotEmpty(sublist)) { 089 mapSlice.put(i, sublist); 090 } 091 } 092 093 return mapSlice; 094 } 095}