apache commons collections

一、引入Maven依赖

<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>

二、常用API说明

以下使用到一些BO

Person.java

public class Person {
    private String username;
    private int age;
    private float stature;//身高
    private boolean sex;//性别
    private List list = new ArrayList();
    private String[] friendsNames;
    private Map<String, String> maps = new HashMap<String, String>();
    private Address address;

    public Person() {

    }
    public Person(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getStature() {
        return stature;
    }

    public void setStature(float stature) {
        this.stature = stature;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    @SuppressWarnings("unchecked")
    public List getList() {
        return list;
    }

    @SuppressWarnings("unchecked")
    public void setList(List list) {
        this.list = list;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public String[] getFriendsNames() {
        return friendsNames;
    }

    public void setFriendsNames(String[] friendsNames) {
        this.friendsNames = friendsNames;
    }

    @Override
    public String toString() {
        return "Person{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", address=" + address +
                '}';
    }
}

Address.java

public class Address {
    private String email;
    private List<String> telephone;
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public List<String> getTelephone() {
        return telephone;
    }
    public void setTelephone(List<String> telephone) {
        this.telephone = telephone;
    }

    @Override
    public String toString() {
        return "Address{" +
                "email='" + email + '\'' +
                ", telephone=" + telephone +
                '}';
    }
}

常用API如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.BufferUtils;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.EnumerationUtils;
import org.apache.commons.collections.FastArrayList;
import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.collections.KeyValue;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.PredicateUtils;
import org.apache.commons.collections.SetUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.TransformerUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.collections.functors.EqualPredicate;
import org.apache.commons.collections.functors.NotNullPredicate;
import org.apache.commons.collections.functors.TruePredicate;
import org.apache.commons.collections.functors.UniquePredicate;
import org.apache.commons.collections.keyvalue.DefaultKeyValue;
import org.apache.commons.collections.list.PredicatedList;

/**
 * Collections java集合框架操作.
 * 常用类
 * ① CollectionUtils 集合操作类
 * ② PredicateUtils 断言Predicate工具类
 * ③ ListUtils List操作工具类
 * ④ MapUtils Map操作工具类
 * ⑤ SetUtils Set集合操作
 * ⑥ IteratorUtils Iterator操作工具类型
 * ⑦ ComparatorUtils
 * ⑧ BufferUtils
 *
 * 其他
 * TransformerUtils
 * FastTreeMap
 * FastHashMap
 * FastArrayList
 */
public class CollectionsDemo {

    private static List<String> list1 = new ArrayList<>(Arrays.asList(new String[]{"1", "2", "3", "1", "5"}));
    private static List<String> list2 = new ArrayList<>(Arrays.asList(new String[]{"2", "3", "1", "4"}));
    private static List<String> list3 = new ArrayList<>(Arrays.asList(new String[]{"1", "2"}));



    private static void testIteratorUtils() {
        List<String> list = IteratorUtils.toList(list1.iterator());
        System.out.println("根据集合迭代器反向获得集合" + list);

        /*
         * ListIterator是一个功能更加强大的, 它继承于Iterator接口,只能用于各种List类型的访问。
         * 双向移动(向前/向后遍历)
         * 产生相对于迭代器在列表中指向的当前位置的前一个和后一个元素的索引.
         * 可以使用set()方法替换它访问过的最后一个元素.
         */
        ListIterator listIterator = IteratorUtils.toListIterator(list.iterator());
        System.out.println(listIterator.next());

        // 获取集合迭代器
        Iterator iterator = IteratorUtils.getIterator(list1);

    }


    /**
     * @MethodName testPredicate
     * @Description Predicate相关的一些操作(PredicateUtils)
     */
    private static void testPredicate() {
        Predicate helloPre = EqualPredicate.getInstance("hello");
        System.out.println("EqualPredicate判断是否相等:" + helloPre.evaluate("hello"));

        Predicate notNullPredicate = NotNullPredicate.getInstance();
        System.out.println("NotNullPredicate判断是否为空, 空字符串返回的是true:" + notNullPredicate.evaluate(null));

        Predicate predicate = UniquePredicate.getInstance();
        // 相当于一开始就对集合做了限制(唯一),后续的操作如果越过了限制就会抛异常
        List<String> list = PredicatedList.decorate(new ArrayList<>(), predicate);
        list.add("zs");
        //list.add("zs");   // 抛出异常  Cannot add Object 'zs' - Predicate  不能重复
        System.out.println(list.size());
    }

    /**
     * @MethodName testSetUtils
     * @Description SetUtils相关测试
     */
    private static void testSetUtils() {
        Set<String> strSet = new HashSet(list1);
        // 转线程安全
        Set<String> synchronizedSet = SetUtils.synchronizedSet(strSet);

        Set<String> orderSet = SetUtils.orderedSet(strSet);
        orderSet.add("67");
        System.out.println("转有序的Set,类似List是有顺序的:" + orderSet);


        Predicate predicate = new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                String str = (String) object;
                return Integer.parseInt(str) > 0;
            }
        };

        Set predicatedSet = SetUtils.predicatedSet(strSet, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                // 这里只能返回true, 返回false会报错, 即断言都大于0才行
                return Integer.parseInt(object.toString()) > 0;
            }
        });
        System.out.println("predicatedSet筛选:" + predicatedSet);

    }

    /**
     * @MethodName testMapUtils
     * @Description MapUtils相关测试
     */
    private static void testMapUtils() {
        Map<String, String> emptyMap = new HashMap();
        Map<String, String> map = new HashMap();
        map.put("宋江", "及时雨");
        map.put("武松", "行者");
        map.put("林冲", "豹子头");
        map.put("李逵", "黑旋风");
        map.put("吴用", "智多星");
        System.out.println("MapUtils.isNotEmpty判断Map不为空:" + MapUtils.isNotEmpty(emptyMap));

        DefaultKeyValue keyValue = new DefaultKeyValue();
        keyValue.setKey("萧让");
        keyValue.setValue("圣手书生");
        MapUtils.putAll(map, new DefaultKeyValue[]{keyValue});
        System.out.println("MapUtils.putAll:" + MapUtils.getString(map, "萧让"));

        // MapUtils有很多getXXX()和getXXXValue()方法,这里就不赘述
        // 转成线程安全的Map
        MapUtils.synchronizedMap(map);
        // 将Map转Properties
        Properties properties = MapUtils.toProperties(map);

        // 这个有什么用呢?
        MapUtils.multiValueMap(map, List.class);
    }

    /**
     * @MethodName testListUtils
     * @Description ListUtils相关测试
     */
    private static void testListUtils() {
        System.out.println("判断两个集合是否相等(采用元素equal):" + ListUtils.isEqualList(list1, list2));
        //取交集
        List<String> intersectionList = (List<String>) ListUtils.intersection(list1, list2);
        System.out.println("两个集合的交集intersection:" + String.join(",", intersectionList));

        // 交集, list1 与 list2 存在相同元素,list1集合只保留list2中存在的元素
        List<String> retainAllList = (List<String>) ListUtils.retainAll(list2, list1);
        System.out.println("两个集合的交集retainAll:" + String.join(",", retainAllList));

        // 并集, 不去重
        List<String> unionList = (List<String>) ListUtils.union(list1, list2);
        System.out.println("两个集合的并集union:" + String.join(",", unionList));

        // list1 - list2 = 剩余元素组成的集合
        List<String> subtractList = (List<String>) ListUtils.subtract(list1, list2);
        System.out.println("list1 - list2:" + String.join(",", subtractList));

        // 转换为线程安全的List
        ListUtils.synchronizedList(list1);

        // 这个不知道用来干什么,名义上是取重的列表合并,但是如果某个列表存在重复元素,合并后并不会剔除
        System.out.println("sum:" + String.join(",", ListUtils.sum(list1, list2)));

        System.out.println("删除列表:" + String.join(",", ListUtils.removeAll(list1, list2)));
    }

    /**
     * @MethodName testCollectionUtils
     * @Description CollectionUtils相关测试
     */
    private static void testCollectionUtils() {

        // 以下的在使用到Predicate时,使用了labmbda表达式
        // 常用的predicate也可以通过PredicateUtils构造出来, 如:
        //返回为null的collection数据
        // CollectionUtils.filter(list1, PredicateUtils.nullPredicate());

        //取交集
        List<String> intersectionList = (List<String>) CollectionUtils.intersection(list1, list2);
        System.out.println("两个集合的交集:" + String.join(",", intersectionList));
        // list1 与 list2 存在相同元素,list1集合只保留list2中存在的元素
        List<String> retainAllList = (List<String>) CollectionUtils.retainAll(list2, list1);
        System.out.println("两个集合的交集:" + String.join(",", retainAllList));


        // 并集, 不去重
        List<String> unionList = (List<String>) CollectionUtils.union(list1, list2);
        System.out.println("两个集合的并集:" + String.join(",", unionList));
        CollectionUtils.addAll(list1, list2.toArray());
        System.out.println("将一个数组或集合中的元素全部添加到另一个集合中:" + list1);

        // 差集, 不去重
        List<String> disjunctionList = (List<String>) CollectionUtils.disjunction(list1, list2);
        System.out.println("两个集合的差集:" + String.join(",", disjunctionList));

        // list1 - list2 = 剩余元素组成的集合
        List<String> subtractList = (List<String>) CollectionUtils.subtract(list1, list2);
        System.out.println("list1 - list2:" + String.join(",", subtractList));

        //统计集合中各元素出现的次数,并Map<Object, Integer>输出
        Map cardinalityMap = CollectionUtils.getCardinalityMap(list1);
        cardinalityMap.forEach((k, v) -> System.out.println(k + ":" + v));

        // a是否b集合子集,a集合大小<=b集合大小
        boolean subCollection = CollectionUtils.isSubCollection(list3, list2);
        System.out.println("a是否b集合子集,a集合大小<=b集合大小:" + subCollection);

        // a是否b集合子集,a集合大小<b集合大小
        boolean properSubCollection = CollectionUtils.isProperSubCollection(list3, list2);
        System.out.println("a是否b集合子集,a集合大小<b集合大小:" + properSubCollection);

        // 两个集合是否相同
        boolean equalCollection = CollectionUtils.isEqualCollection(list3, list2);
        System.out.println("两个集合是否相同:" + equalCollection);

        // 某元素在集合中出现的次数
        int cardinality = CollectionUtils.cardinality("1", list1);
        System.out.println("某元素在集合中出现的次数:" + cardinality);

        // 返回集合中满足函数式的唯一元素,只返回最先处理符合条件的唯一元素
        Object value = CollectionUtils.find(list1, itm -> {
            return Integer.valueOf(itm.toString()) > 1;
        });
        System.out.println("find:" + value);

        //返回符合条件的collection
        Collection resultSelect = CollectionUtils.select(list1, itm -> Integer.valueOf(itm.toString()) > 1);
        System.out.println("select:" + String.join(",", resultSelect));

        //和select结果相反,返回不符合条件的collection
        Collection resultSelectReject = CollectionUtils.selectRejected(list1, itm -> Integer.valueOf(itm.toString()) > 1);
        System.out.println("selectRejected:" + String.join(",", resultSelectReject));

        //判断list1是否包含符合条件的元素
        boolean resultExists = CollectionUtils.exists(list1, itm -> Integer.valueOf(itm.toString()) > 2);
        System.out.println("exists:" + resultExists);

        //返回list1符合条件的个数
        int resultMatchNum = CollectionUtils.countMatches(list1, itm -> Integer.valueOf(itm.toString()) > 1);
        System.out.println("countMatches:" + resultMatchNum);

        //返回list1且只包含数据大于2
        CollectionUtils.filter(list1, itm -> Integer.valueOf(itm.toString()) > 2);
        System.out.println("filter:" + String.join(",", list1));

        //这个比较难理解,如果后面predicate都满足,则返回list1,
        Collection resultCollect = CollectionUtils.predicatedCollection(list1, itm -> {
            //Returns a predicated (validating) collection backed by the given collection.
            return Integer.valueOf(itm.toString()) > 0;
        });
        System.out.println("predicatedCollection:" + String.join(",", resultCollect));

        //对集合中的对象中的某一属性进行批量更新,closure为需要更新的属性对象
        List<Person> personList = new ArrayList();
        Person person1 = new Person();
        person1.setAge(25);
        personList.add(person1);
        Person person2 = new Person();
        person2.setAge(17);
        personList.add(person2);
        CollectionUtils.forAllDo(personList, new Closure() {
            @Override
            public void execute(Object input) {
                Person pn = (Person) input;
                pn.setAge(pn.getAge() + 1);
            }
        });
        System.out.println("forAllDo:" + personList.get(0).getAge());

        // collect底层调用的transform方法, 将所有元素进行处理,并返回新的集合
        List<Integer> collection = (List<Integer>) CollectionUtils.collect(list1, new Transformer() {
            @Override
            public Object transform(Object o) {
                int i = Integer.parseInt((String) o);
                return ++i;
            }
        });
        System.out.println("collect:" + collection);

        System.out.println("判断集合是否为空:" + CollectionUtils.isNotEmpty(list1));
        System.out.println("判断两个集合是否有相同元素:" + CollectionUtils.containsAny(list1, list2));

        System.out.println("返回集合中指定下标元素:" + CollectionUtils.get(list1, 2));
        System.out.println("删除相同元素后list1剩余元素:" + CollectionUtils.removeAll(list1, list2));
    }


    public static void main(String[] args) {
        //CollectionsDemo.testCollectionUtils();
        //CollectionsDemo.testListUtils();
        //CollectionsDemo.testMapUtils();
        //CollectionsDemo.testSetUtils();
        //CollectionsDemo.testPredicate();
        //CollectionsDemo.testIteratorUtils();
    }
}

 

posted @ 2020-10-25 13:02  codedot  阅读(2353)  评论(0编辑  收藏  举报