commons-collections4集合类库使用

添加maven依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

 

CollectionUtils

// 除非元素为null,否则向集合添加元素
CollectionUtils.addIgnoreNull(personList,null);
// 将两个已排序的集合a和b合并为一个已排序的列表,以便保留元素的自然顺序
CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b)
// 将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序
CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)
// 返回该个集合中是否含有至少有一个元素
CollectionUtils.containsAny(Collection<?> coll1, T... coll2)
// 如果参数是null,则返回不可变的空集合,否则返回参数本身。(很实用 ,最终返回List EMPTY_LIST = new EmptyList<>())
CollectionUtils.emptyIfNull(Collection<T> collection)
// 空安全检查指定的集合是否为空
CollectionUtils.isEmpty(Collection<?> coll)
// 空安全检查指定的集合是否为空
CollectionUtils.isNotEmpty(Collection<?> coll)
// 反转给定数组的顺序
CollectionUtils.reverseArray(Object[] array);
// 差集
CollectionUtils.subtract(Iterable<? extends O> a, Iterable<? extends O> b)
// 并集
CollectionUtils.union(Iterable<? extends O> a, Iterable<? extends O> b)
// 交集
CollectionUtils.intersection(Collection a, Collection b)
// 交集的补集(析取)
CollectionUtils.disjunction(Collection a, Collection b)
// 检查集合是否包含给定集合    
CollectionUtils.isSubCollection(Collection<?> a, Collection<?> b)    
// 用于过滤列表以移除不满足由谓词传递提供的条件的对象
CollectionUtils.filter(Iterable<T> collection, Predicate<? super T> predicate)
// 用于过滤列表以移除满足谓词传递提供的条件的对象
CollectionUtils.filterInverse(Iterable<T> collection, Predicate<? super T> predicate) 

 

Bag

使用场景: 比如我们需要具体知道每个元素出现的次数的时候,并且实现快速去重,使用Bag会非常便捷

对应的BagUtils,能提供 BagUtils.EMPTY_BAG、synchronizedBag、unmodifiableBag 等编程同步、只读的快捷方法

public class BagApp {

    public static void main(String[] args) {
        Bag<String> bag = new HashBag();

        // 一次性放多个元素
        bag.add("Bag", 5);
        // 对集合内元素去重
        System.out.println(bag.uniqueSet());

        for (int i = 1; i < 5; i++) {
            bag.add("Bag" + i);
        }

        Iterator<String> iterator = bag.iterator();
        while (iterator.hasNext()) {
            System.out.printf(iterator.next() + ",");
        }
        System.out.println();
        
        // 获取集合元素个数
        System.out.println(bag.size());
        // 获取集合内指定元素出现的次数
        System.out.println(bag.getCount("Bag"));
    }

}

程序运行结果

[Bag]
Bag4,Bag3,Bag2,Bag1,Bag,Bag,Bag,Bag,Bag,
9
5

 

LRUMap

public class LRUMapApp {

    public static void main(String[] args) {
        LRUMap<String, String> lruMap = new LRUMap<>(3);

        System.out.println("size=" + lruMap.size());
        System.out.println("maxSize=" + lruMap.maxSize());
        System.out.println("isFull=" + lruMap.isFull());

        System.out.println();
        lruMap.put("id", "1");
        lruMap.put("code", "A0001");
        lruMap.put("name", "第一个");

        System.out.println(lruMap);
        System.out.println("size=" + lruMap.size());
        System.out.println("maxSize=" + lruMap.maxSize());
        System.out.println("isFull=" + lruMap.isFull());

        System.out.println();
        // 使用了id, 所以key为id不会被挤出去, code被挤出去
        lruMap.get("id");

        lruMap.put("email", "XXX");
        System.out.println(lruMap);
        System.out.println("size=" + lruMap.size());
        System.out.println("maxSize=" + lruMap.maxSize());
        System.out.println("isFull=" + lruMap.isFull());
    }

}

程序运行结果

size=0
maxSize=3
isFull=false

{id=1, code=A0001, name=第一个}
size=3
maxSize=3
isFull=true

{name=第一个, id=1, email=XXX}
size=3
maxSize=3
isFull=true

 

SingletonMap

public class SingletonMapApp {

    public static void main(String[] args) {
        SingletonMap<String, String> singletonMap = new SingletonMap<>();

        System.out.println(singletonMap);
        System.out.println(singletonMap.size());
        System.out.println(singletonMap.maxSize());

        // 哪怕一个都没有 也不能设置值
//        singletonMap.put("name","Answer"); // Cannot put new key/value pair - Map is fixed size singleton

        // 虽然不能再放key 但可以改值
        singletonMap.setValue("Answer");
        System.out.println(singletonMap);

        // 一般建议在构造的时候,就给key和value赋值  如下:
        singletonMap = new SingletonMap<>("name","Jaemon");
        System.out.println(singletonMap);
    }

}

程序运行结果

{null=null}
1
1
{null=Answer}
{name=Jaemon}

 

MapUtils

emptyIfNull

// 旧写法
if (map != null) {
     return Collections.emptyMap();
 }
// 新写法
return MapUtils.emptyIfNull(map);

fixedSizeMap、fixedSizeSortedMap

把当前map设置为定长,即:不能在put新的key

IterableMap<String, Object> result = MapUtils.fixedSizeMap(map);

public static void main(String[] args) {
    Map<String, String> map = Maps.newHashMap();
    map.put("key1", "A");
    map.put("key2", "B");

    IterableMap<String, String> result = MapUtils.fixedSizeMap(map);
    result.put("key2", "C");
    // 报错: java.lang.IllegalArgumentException: Cannot put new key/value pair - Map is fixed size
    //        result.put("key3", "C");
    System.out.println(result);
}

invertMap

  • 对调key和value的值

iterableMap

构建一个iterableMap,然后方便遍历、删除等等

populateMap

  • 能很方便向Map里面放值,并且支持定制化key和value,还是挺好用的
public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("key1", "value1");

    // 序列化 根据提供的values,按照后面规则把key都生成出来然后直接放进去
    MapUtils.populateMap(map, Arrays.asList("a", "b", "c"), e -> "key-" + e);
    // {key1=value1, key-a=a, key-c=c, key-b=b}
    System.out.println(map);
    // 可以在上面的理论上 对value进行进一步操作  不能采用map.values() 否则由于并发修改异常
    // MapUtils.populateMap(map, map.values(), e -> e, e -> "value-" + e); //java.util.ConcurrentModificationException
    MapUtils.populateMap(map, Arrays.asList("a", "b", "c"), e -> e, e -> "value-" + e);
	// {key1=value1, key-a=a, a=value-a, b=value-b, c=value-c, key-c=c, key-b=b}
    System.out.println(map);
}

toProperties

可以有非常简便的转化

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value2");

    Properties properties = MapUtils.toProperties(map);
    // {key3=value2, key2=value2, key1=value1}
    System.out.println(properties); 
}

 

SetUtils

  • difference: 找到两个set之间的不同元素(返回的是第一个set里有的,但是第二个set里没有的元素们)

  • disjunction: 会返回第一个set和第二个有差异的所有元素们

  • emptyIfNull: 见上MapUtils类似方法

  • newIdentityHashSet: 可以实例化出一个newIdentityHashSet

  • isEqualSet: 两个set里面的元素是否都一样(长度一样、元素一样),有时候判断还是非常有用的

  • union: 合并两个set,生成一个新的set

 

ListUtils

  • emptyIfNull: 同上

  • defaultIfNull: 可以在为null的时候,自己给个默认值返回

  • fixedSizeList: 不解释

  • hashCodeForList: 给List吧它的HashCode计算出来

  • intersection: 取交集,生成一个新的List

  • partition: 切割 把一个大的List切割成多个List 非常好用

    • 常用场景:有10000个id需要批量查询,我们可以切割一下,200个发一次请求去查询一次
  • subtract: 相当于做减法,用第一个List除去第二个list里含有的元素 ,然后生成一个新的list

  • sum: 把两个List的元素相加起来 注意:相同的元素不会加两次 生成一个新的List

  • union: 这个和sum方法不一样,它不带去重的功能。内部调用的addAll方法,但是生成一个新的List

 

Reference

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jaemon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值