当前位置 : 首页 » 文章分类 :  开发  »  Apache-Commons-Collections 使用笔记

Apache-Commons-Collections 使用笔记

Apache-Commons-Collections 使用笔记

Apache Commons Collections 官网
https://commons.apache.org/proper/commons-collections/

Apache Commons Collections 4.2 官方API文档
https://commons.apache.org/proper/commons-collections/javadocs/api-release/index.html


MapUtils

package org.apache.commons.collections4;
public class MapUtils

isNotEmpty() 集合非空

public static boolean isNotEmpty(Map<?,?> map)

isEmpty() 集合判空

public static boolean isEmpty(Map<?,?> map)


CollectionUtils

isNotEmpty 集合判空

CollectionUtils.isNotEmpty()

判断集合只包含空元素

用 cn.hutool.core.collection.removeBlank 先删除 blank 元素,再判空,注意 removeBlank 会直接修改原集合

CollectionUtils.isEmpty(CollectionUtil.removeBlank(col))

MultiValuedMap

一个 key 中可以存放多个 value 的 Map,类似 Spring 的 MultiValueMap

@Test
public void test() {
    MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
    String key1 = "key1";
    map.put(key1, "A");
    map.put(key1, "B");
    map.put(key1, "C");
    Collection<String> values = map.get(key1);
    Assertions.assertEquals(3, values.size());
    System.out.println(map);
}

ListOrderedSet

ListOrderedSet 结合了 Set(元素唯一性)和 List(有序性)的特性。
元素唯一性​​:不允许重复元素(符合 Set 特性)。
顺序保留​​:严格按照元素添加顺序存储(符合 List 特性),indexOf 方法可查询元素在 set 中的序号。

@Test
public void testListOrderedSet() {
    ListOrderedSet<String> orderedSet = new ListOrderedSet<>();
    orderedSet.add("Apple");  // 添加成功,返回 true
    orderedSet.add("Banana"); // 添加成功
    orderedSet.add("Apple");  // 重复元素,添加失败,返回 false
    orderedSet.add("Cherry"); // 添加成功

    System.out.println(orderedSet);
    System.out.println(orderedSet.get(0)); // Apple
    System.out.println(orderedSet.get(orderedSet.size() - 1)); // Cherry
    System.out.println(orderedSet.indexOf("Apple")); // 0
    System.out.println(orderedSet.indexOf("Cherry")); // 2
}

上一篇 Google-Guava 使用笔记

下一篇 Apache-Commons-Lang 使用笔记

阅读
评论
366
阅读预计1分钟
创建日期 2018-06-29
修改日期 2025-09-15
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论