- 引入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
- 案例1
import org.apache.commons.collections4.MapUtils;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class MapUtilsTest {
/**
* 判断map不为空(null/size>0)
*/
@Test
public void test1(){
Map<String,String> map = new HashMap<>();
System.out.println(MapUtils.isEmpty(map));// 没有元素就true
System.out.println(MapUtils.isNotEmpty(map));
// 获取map中key=a的值并转为integer
System.out.println(MapUtils.getInteger(map, "a"));
}
}
- 案例2
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CollectionsUtilsTest {
/**
* 交集、并集、差集
*/
@Test
public void test2(){
List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("c");
list2.add("1");
list2.add("2");
// 取交集 ,c
System.out.println(CollectionUtils.intersection(list1, list2));
// 并集, a,b,c,1,2
System.out.println(CollectionUtils.union(list1, list2));
// 差集,a,b
System.out.println(CollectionUtils.subtract(list1, list2));
// 1,2
System.out.println(CollectionUtils.subtract(list2, list1));
}
/**
* 判断list、set不为空(null/size>0)
*/
@Test
public void test1(){
List<String> list = new ArrayList<>();
System.out.println(CollectionUtils.isEmpty(list));// true
// 反过来
System.out.println(CollectionUtils.isNotEmpty(list));// false
}
}
标签:collections4,list1,System,commons,使用,println,import,list2,out
From: https://www.cnblogs.com/chniny/p/16750704.html