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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章