首页

关于cglib的CollectionUtils类集工具类实现Map的KV的位置对调、List转Map及过滤等操作

标签:CollectionUtils,cglib,集合工具类,List转换Map,过滤集合黑名单     发布时间:2018-03-25   

一、前言

关于cglib源码包(相关jar下载)分别基于net.sf.cglib.core.CollectionUtils集合工具类,实现基于net.sf.cglib.core.Transformer转换接口对任何集合进行转换Map处理、将Map的Key/Value倒换互存位置reverse、基于net.sf.cglib.core.Predicate接口对类集合任何关键词内容进行过滤、对基于net.sf.cglib.core.Transformer转换接口任何类型转换为List、通过将List转换Map获取其索引键值getIndexMap等,详情参见示例说明。

二、示例代码

1.CollectionUtils类

 package net.sf.cglib.core;@b@@b@import java.util.*;@b@import java.lang.reflect.Array;@b@@b@public class CollectionUtils {@b@    private CollectionUtils() { }@b@@b@    public static Map bucket(Collection c, Transformer t) {@b@        Map buckets = new HashMap();@b@        for (Iterator it = c.iterator(); it.hasNext();) {@b@            Object value = (Object)it.next();@b@            Object key = t.transform(value);@b@            List bucket = (List)buckets.get(key);@b@            if (bucket == null) {@b@                buckets.put(key, bucket = new LinkedList());@b@            }@b@            bucket.add(value);@b@        }@b@        return buckets;@b@    }@b@@b@    public static void reverse(Map source, Map target) {@b@        for (Iterator it = source.keySet().iterator(); it.hasNext();) {@b@            Object key = it.next();@b@            target.put(source.get(key), key);@b@        }@b@    }@b@@b@    public static Collection filter(Collection c, Predicate p) {@b@        Iterator it = c.iterator();@b@        while (it.hasNext()) {@b@            if (!p.evaluate(it.next())) {@b@                it.remove();@b@            }@b@        }@b@        return c;@b@    }@b@@b@    public static List transform(Collection c, Transformer t) {@b@        List result = new ArrayList(c.size());@b@        for (Iterator it = c.iterator(); it.hasNext();) {@b@            result.add(t.transform(it.next()));@b@        }@b@        return result;@b@    }@b@@b@    public static Map getIndexMap(List list) {@b@        Map indexes = new HashMap();@b@        int index = 0;@b@        for (Iterator it = list.iterator(); it.hasNext();) {@b@            indexes.put(it.next(), new Integer(index++));@b@        }@b@        return indexes;@b@    }@b@}

2.Transformer转换接口

package net.sf.cglib.core;@b@@b@public interface Transformer {@b@    Object transform(Object value);@b@}

3.Predicate过滤器接口

package net.sf.cglib.core;@b@@b@public interface Predicate {@b@    boolean evaluate(Object arg);@b@}