本文共 2531 字,大约阅读时间需要 8 分钟。
@RunWith(JUnit4.class)public class SimpleTest { /** ** */ @Test public void testGuava() { // basicOperate(); CollectionOperate(); } private void CollectionOperate() { /* * set集合交集, 并集, 差集 * */ HashSetcom.google.guava *guava *19.0 *set1 = Sets.newHashSet(1, 2, 3, 4, 5); HashSet set2 = Sets.newHashSet(4, 5, 6, 7, 8); //交集 Sets.SetView intersection = Sets.intersection(set1, set2);//45 //并集 Sets.SetView union = Sets.union(set1, set2);//12345678 //差集,set1比set2多出的部分 Sets.SetView difference1 = Sets.difference(set1, set2);//123 Sets.SetView difference2 = Sets.difference(set2, set1);//678 } private void typeTrans() { /* * 集合类型转换 * */ List integers = Lists.newArrayList(1, 2, 3, 4); //注意包路径 List strings = com.google.common.collect.Lists.transform(integers, Functions.toStringFunction()); } private void basicOperate() { /* * 一般的可变集合直接使用Maps./Lists./Sets.等方法直接调用 * 不可变集合如下所示: * (1)在多线程操作下,是线程安全的 * (2)所有不可变集合会比可变集合更有效的利用资源 * (3)中途不可改变,使用add、remove等方法直接抛异常 * */ ImmutableList list = ImmutableList.of("a", "b"); ImmutableMap map = ImmutableMap.of(1, "a", 2, "b", 3, "c"); ImmutableSet set = ImmutableSet.of("a", "a");//排重 /* * 将list作为value,任意不重复主键作为key形成一个map
转载地址:http://utgzi.baihongyu.com/