java list merge_通过集合工具类CollectionUtils实现合并数组、属性至集合或Map集、指定类型查找等相关操作...

一、前言

这边通过定义CollectionUtils集合工具类,实现对数组转序列arrayToList、合并数组为集合mergeArrayIntoCollection、合并属性为Map的方法mergePropertiesIntoMap、集合类型查询findValueOfType等操作。

二、代码示例import java.util.Arrays;@b@import java.util.Collection;@b@import java.util.Enumeration;@b@import java.util.Iterator;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Properties;@b@@b@@b@public abstract class CollectionUtils {@b@@b@/**@b@ * Return true if the supplied Collection is null@b@ * or empty. Otherwise, return false.@b@ * @param collection the Collection to check@b@ * @return whether the given Collection is empty@b@ */@b@@SuppressWarnings("rawtypes")@b@public static boolean isEmpty(Collection collection) {@b@return (collection == null || collection.isEmpty());@b@}@b@@b@/**@b@ * Return true if the supplied Map is null@b@ * or empty. Otherwise, return false.@b@ * @param map the Map to check@b@ * @return whether the given Map is empty@b@ */@b@@SuppressWarnings("rawtypes")@b@public static boolean isEmpty(Map map) {@b@return (map == null || map.isEmpty());@b@}@b@@b@/**@b@ * Convert the supplied array into a List. A primitive array gets@b@ * converted into a List of the appropriate wrapper type.@b@ * 

null source value will be converted to an@b@ * empty List.@b@ * @param source the (potentially primitive) array@b@ * @return the converted List result@b@ * @see ObjectUtils#toObjectArray(Object)@b@ */@b@@SuppressWarnings("rawtypes")@b@public static List arrayToList(Object source) {@b@return Arrays.asList(ObjectUtils.toObjectArray(source));@b@}@b@@b@/**@b@ * Merge the given array into the given Collection.@b@ * @param array the array to merge (may be null)@b@ * @param collection the target Collection to merge the array into@b@ */@b@@SuppressWarnings({"rawtypes","unchecked"})@b@public static void mergeArrayIntoCollection(Object array, Collection collection) {@b@if (collection == null) {@b@throw new IllegalArgumentException("Collection must not be null");@b@}@b@Object[] arr = ObjectUtils.toObjectArray(array);@b@for (Object elem : arr) {@b@collection.add(elem);@b@}@b@}@b@@b@/**@b@ * Merge the given Properties instance into the given Map,@b@ * copying all properties (key-value pairs) over.@b@ * 

Uses Properties.propertyNames() to even catch@b@ * default properties linked into the original Properties instance.@b@ * @param props the Properties instance to merge (may be null)@b@ * @param map the target Map to merge the properties into@b@ */@b@@SuppressWarnings({"unchecked","rawtypes"})@b@public static void mergePropertiesIntoMap(Properties props, Map map) {@b@if (map == null) {@b@throw new IllegalArgumentException("Map must not be null");@b@}@b@if (props != null) {@b@for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {@b@String key = (String) en.nextElement();@b@Object value = props.getProperty(key);@b@if (value == null) {@b@// Potentially a non-String value...@b@value = props.get(key);@b@}@b@map.put(key, value);@b@}@b@}@b@}@b@@b@@b@/**@b@ * Check whether the given Iterator contains the given element.@b@ * @param iterator the Iterator to check@b@ * @param element the element to look for@b@ * @return true if found, false else@b@ */@b@public static boolean contains(@SuppressWarnings("rawtypes") Iterator iterator, Object element) {@b@if (iterator != null) {@b@while (iterator.hasNext()) {@b@Object candidate = iterator.next();@b@if (ObjectUtils.nullSafeEquals(candidate, element)) {@b@return true;@b@}@b@}@b@}@b@return false;@b@}@b@@b@/**@b@ * Check whether the given Enumeration contains the given element.@b@ * @param enumeration the Enumeration to check@b@ * @param element the element to look for@b@ * @return true if found, false else@b@ */@b@public static boolean contains(@SuppressWarnings("rawtypes") Enumeration enumeration, Object element) {@b@if (enumeration != null) {@b@while (enumeration.hasMoreElements()) {@b@Object candidate = enumeration.nextElement();@b@if (ObjectUtils.nullSafeEquals(candidate, element)) {@b@return true;@b@}@b@}@b@}@b@return false;@b@}@b@@b@/**@b@ * Check whether the given Collection contains the given element instance.@b@ * 

Enforces the given instance to be present, rather than returning@b@ * true for an equal element as well.@b@ * @param collection the Collection to check@b@ * @param element the element to look for@b@ * @return true if found, false else@b@ */@b@public static boolean containsInstance(@SuppressWarnings("rawtypes") Collection collection, Object element) {@b@if (collection != null) {@b@for (Object candidate : collection) {@b@if (candidate == element) {@b@return true;@b@}@b@}@b@}@b@return false;@b@}@b@@b@/**@b@ * Return true if any element in 'candidates' is@b@ * contained in 'source'; otherwise returns false.@b@ * @param source the source Collection@b@ * @param candidates the candidates to search for@b@ * @return whether any of the candidates has been found@b@ */@b@@SuppressWarnings("rawtypes")@b@public static boolean containsAny( Collection source, Collection candidates) {@b@if (isEmpty(source) || isEmpty(candidates)) {@b@return false;@b@}@b@for (Object candidate : candidates) {@b@if (source.contains(candidate)) {@b@return true;@b@}@b@}@b@return false;@b@}@b@@b@/**@b@ * Return the first element in 'candidates' that is contained in@b@ * 'source'. If no element in 'candidates' is present in@b@ * 'source' returns null. Iteration order is@b@ * {@link Collection} implementation specific.@b@ * @param source the source Collection@b@ * @param candidates the candidates to search for@b@ * @return the first present object, or null if not found@b@ */@b@@SuppressWarnings("rawtypes")@b@public static Object findFirstMatch(Collection source, Collection candidates) {@b@if (isEmpty(source) || isEmpty(candidates)) {@b@return null;@b@}@b@for (Object candidate : candidates) {@b@if (source.contains(candidate)) {@b@return candidate;@b@}@b@}@b@return null;@b@}@b@@b@/**@b@ * Find a single value of the given type in the given Collection.@b@ * @param collection the Collection to search@b@ * @param type the type to look for@b@ * @return a value of the given type found if there is a clear match,@b@ * or null if none or more than one such value found@b@ */@b@@SuppressWarnings("unchecked")@b@public static  T findValueOfType(Collection> collection, Class type) {@b@if (isEmpty(collection)) {@b@return null;@b@}@b@T value = null;@b@for (Object element : collection) {@b@if (type == null || type.isInstance(element)) {@b@if (value != null) {@b@// More than one value found... no clear single value.@b@return null;@b@}@b@value = (T) element;@b@}@b@}@b@return value;@b@}@b@@b@/**@b@ * Find a single value of one of the given types in the given Collection:@b@ * searching the Collection for a value of the first type, then@b@ * searching for a value of the second type, etc.@b@ * @param collection the collection to search@b@ * @param types the types to look for, in prioritized order@b@ * @return a value of one of the given types found if there is a clear match,@b@ * or null if none or more than one such value found@b@ */@b@public static Object findValueOfType(Collection> collection, Class>[] types) {@b@if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {@b@return null;@b@}@b@for (Class> type : types) {@b@Object value = findValueOfType(collection, type);@b@if (value != null) {@b@return value;@b@}@b@}@b@return null;@b@}@b@@b@/**@b@ * Determine whether the given Collection only contains a single unique object.@b@ * @param collection the Collection to check@b@ * @return true if the collection contains a single reference or@b@ * multiple references to the same instance, false else@b@ */@b@@SuppressWarnings("rawtypes")@b@public static boolean hasUniqueObject(Collection collection) {@b@if (isEmpty(collection)) {@b@return false;@b@}@b@boolean hasCandidate = false;@b@Object candidate = null;@b@for (Object elem : collection) {@b@if (!hasCandidate) {@b@hasCandidate = true;@b@candidate = elem;@b@}@b@else if (candidate != elem) {@b@return false;@b@}@b@}@b@return true;@b@}@b@@b@/**@b@ * Find the common element type of the given Collection, if any.@b@ * @param collection the Collection to check@b@ * @return the common element type, or null if no clear@b@ * common type has been found (or the collection was empty)@b@ */@b@@SuppressWarnings("rawtypes")@b@public static Class> findCommonElementType(Collection collection) {@b@if (isEmpty(collection)) {@b@return null;@b@}@b@Class> candidate = null;@b@for (Object val : collection) {@b@if (val != null) {@b@if (candidate == null) {@b@candidate = val.getClass();@b@}@b@else if (candidate != val.getClass()) {@b@return null;@b@}@b@}@b@}@b@return candidate;@b@}@b@@b@/**@b@ * Adapts an enumeration to an iterator.@b@ * @param enumeration the enumeration@b@ * @return the iterator@b@ */@b@public static  Iterator toIterator(Enumeration enumeration) {@b@return new EnumerationIterator(enumeration);@b@}@b@@b@@b@/**@b@ * Iterator wrapping an Enumeration.@b@ */@b@private static class EnumerationIterator implements Iterator {@b@@b@private Enumeration enumeration;@b@@b@public EnumerationIterator(Enumeration enumeration) {@b@this.enumeration = enumeration;@b@}@b@@b@public boolean hasNext() {@b@return this.enumeration.hasMoreElements();@b@}@b@@b@public E next() {@b@return this.enumeration.nextElement();@b@}@b@@b@public void remove() throws UnsupportedOperationException {@b@throw new UnsupportedOperationException("Not supported");@b@}@b@}@b@@b@}

以下是一个简单的Java工具类,可以使用EasyExcel库将数据填充到Excel中,并合并具有相同属性的行。 ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.write.merge.AbstractMergeStrategy; import com.alibaba.excel.write.merge.LoopMergeStrategy; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteWorkbook; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * EasyExcel填充数据并合并相同属性工具类 */ public class EasyExcelUtil { /** * 填充数据并合并相同属性的行 * * @param filePath 文件路径 * @param sheetName 工作表名称 * @param header 头部 * @param data 数据 * @param mergeIndex 需要合并的列的索引 */ public static void fillAndMerge(String filePath, String sheetName, List<String> header, List<List<String>> data, int mergeIndex) { // 创建一个Excel写工具 ExcelWriter writer = EasyExcel.write(filePath).build(); // 创建一个工作表 WriteSheet sheet = EasyExcel.writerSheet(sheetName).build(); // 将数据按照相同的属性分组 Map<String, List<List<String>>> groupMap = groupByProperty(data, mergeIndex); // 遍历分组后的数据,将每个分组写入Excel中 groupMap.forEach((property, groupData) -> { // 写入头部 writer.writeHeader(header, sheet); // 写入数据 writer.write(groupData, sheet); // 合并相同属性的行 AbstractMergeStrategy mergeStrategy = new LoopMergeStrategy(property, mergeIndex); mergeStrategy.merge(sheet, writer); }); // 关闭Excel写工具 writer.finish(); } /** * 将数据按照指定属性分组 * * @param data 数据 * @param mergeIndex 需要合并的列的索引 * @return 分组后的数据,Map的键为属性值,值为数据列表 */ private static Map<String, List<List<String>>> groupByProperty(List<List<String>> data, int mergeIndex) { return data.stream().collect(Collectors.groupingBy(row -> row.get(mergeIndex))); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { // 准备数据 List<String> header = new ArrayList<>(); header.add("姓名"); header.add("年龄"); header.add("性别"); List<List<String>> data = new ArrayList<>(); data.add(Arrays.asList("张三", "20", "男")); data.add(Arrays.asList("李四", "22", "男")); data.add(Arrays.asList("王五", "20", "女")); data.add(Arrays.asList("赵六", "22", "女")); // 填充数据并合并相同属性的行 EasyExcelUtil.fillAndMerge("test.xlsx", "Sheet1", header, data, 2); } } ``` 在这个示例中,我们将数据按照性别分组,并将具有相同性别的行合并在一起。因此,输出的Excel文件将具有两行,每行具有两个单元格,显示相同性别的人的姓名和年龄。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值