005-guava 集合-集合工具类-java.util.Collections中未包含的集合工具[Maps,Lists,Sets],Iterables、Multisets、Multimaps、Tables

一、概述

  工具类与特定集合接口的对应关系归纳如下:

集合接口 属于JDK还是Guava 对应的Guava工具类
Collection JDK Collections2:不要和java.util.Collections混淆
List JDK Lists
Set JDK Sets
SortedSet JDK Sets
Map JDK Maps
SortedMap JDK Maps
Queue JDK Queues
Multiset Guava Multisets
Multimap Guava Multimaps
BiMap Guava Maps
Table Guava Tables

 

二、使用

2.1、静态工厂方法-创建型工具类

  guava 为创建基本类型集合提供上述工具类创建,为自建集合类型提供create方式创建,工具类如上

    @Test
    public void testNewInstance() {
        //jdk 7 之前
        List<String> list1 = new ArrayList<String>();
        //jdk 7 之后
        List<String> list2 = new ArrayList<>();
        //Guava的静态工厂方法 
        ArrayList<String> list3 = Lists.newArrayList();
        ArrayList<String> list4 = Lists.newArrayList("a","b");
        ArrayList<String> list5 = Lists.newArrayListWithCapacity(100);
        // guava 集合创建
        Multiset<String> multiset = HashMultiset.create();
    }

   Guava引入的新集合类型没有暴露原始构造器,也没有在工具类中提供初始化方法。而是直接在集合类中提供了静态工厂方法

2.2、工具类-Iterables

  在可能的情况下,Guava提供的工具方法更偏向于接受Iterable而不是Collection类型。在Google,对于不存放在主存的集合——比如从数据库或其他数据中心收集的结果集,因为实际上还没有攫取全部数据,这类结果集都不能支持类似size()的操作 ——通常都不会用Collection类型来表示。

  因此,很多你期望的支持所有集合的操作都在Iterables类中。大多数Iterables方法有一个在Iterators类中的对应版本,用来处理Iterator。

常规方法

concat(Iterable<Iterable>) 串联多个iterables的懒视图* concat(Iterable...)
frequency(Iterable, Object) 返回对象在iterable中出现的次数 与Collections.frequency (Collection,   Object)比较;Multiset
partition(Iterable, int) 把iterable按指定大小分割,得到的子集都不能进行修改操作 Lists.partition(List, int)paddedPartition(Iterable, int)
getFirst(Iterable, T default) 返回iterable的第一个元素,若iterable为空则返回默认值 与Iterable.iterator(). next()比较;FluentIterable.first()
getLast(Iterable) 返回iterable的最后一个元素,若iterable为空则抛出NoSuchElementException getLast(Iterable, T default)
FluentIterable.last()
elementsEqual(Iterable, Iterable) 如果两个iterable中的所有元素相等且顺序一致,返回true 与List.equals(Object)比较
unmodifiableIterable(Iterable) 返回iterable的不可变视图 与Collections. unmodifiableCollection(Collection)比较
limit(Iterable, int) 限制iterable的元素个数限制给定值 FluentIterable.limit(int)
getOnlyElement(Iterable) 获取iterable中唯一的元素,如果iterable为空或有多个元素,则快速失败 getOnlyElement(Iterable, T default)

示例

    @Test
    public void testIterables() {
        ArrayList<String> ab = Lists.newArrayList("a","b");
        ArrayList<String> bc = Lists.newArrayList("b","c");
        Iterable<String> concat = Iterables.concat(ab, bc);
        System.out.println(concat);//[a, b, b, c]
        Iterable<List<String>> lists = Iterables.paddedPartition(ab,1);
        System.out.println(lists);//[[a], [b]]
    }

其他操作方法

与Collection方法相似的工具方法

方法 类似的Collection方法 等价的FluentIterable方法
addAll(Collection addTo,   Iterable toAdd) Collection.addAll(Collection)  
contains(Iterable, Object) Collection.contains(Object) FluentIterable.contains(Object)
removeAll(Iterable   removeFrom, Collection toRemove) Collection.removeAll(Collection)  
retainAll(Iterable   removeFrom, Collection toRetain) Collection.retainAll(Collection)  
size(Iterable) Collection.size() FluentIterable.size()
toArray(Iterable, Class) Collection.toArray(T[]) FluentIterable.toArray(Class)
isEmpty(Iterable) Collection.isEmpty() FluentIterable.isEmpty()
get(Iterable, int) List.get(int) FluentIterable.get(int)
toString(Iterable) Collection.toString() FluentIterable.toString()

2.3、工具类-FluentIterable

除了上面提到的方法,FluentIterable还有一些便利方法用来把自己拷贝到不可变集合

ImmutableList  
ImmutableSet toImmutableSet()
ImmutableSortedSet toImmutableSortedSet(Comparator)

2.4、工具类-LIsts、Sets、Maps

Lists

方法 描述
partition(List, int) 把List按指定大小分割
reverse(List) 返回给定List的反转视图。注: 如果List是不可变的,考虑改用ImmutableList.reverse()

Sets

集合理论方法

我们提供了很多标准的集合运算(Set-Theoretic)方法,这些方法接受Set参数并返回SetView,可用于:

  • 直接当作Set使用,因为SetView也实现了Set接口;
  • copyInto(Set)拷贝进另一个可变集合;
  • immutableCopy()对自己做不可变拷贝。
方法
union(Set, Set)
intersection(Set, Set)
difference(Set, Set)
symmetricDifference(Set,   Set)

其他Set工具方法

方法 描述 另请参见
cartesianProduct(List<Set>) 返回所有集合的笛卡儿积 cartesianProduct(Set...)
powerSet(Set) 返回给定集合的所有子集  

Maps

uniqueIndex

Maps.uniqueIndex(Iterable,Function)通常针对的场景是:有一组对象,它们在某个属性上分别有独一无二的值,而我们希望能够按照这个属性值查找对象——译者注:这个方法返回一个Map,键为Function返回的属性值,值为Iterable中相应的元素,因此我们可以反复用这个Map进行查找操作。

比方说,我们有一堆字符串,这些字符串的长度都是独一无二的,而我们希望能够按照特定长度查找字符串:

    class Person {
        private String name;
        private Integer age;

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    @Test
    public void testMapsuniqueIndex() {
        ArrayList<Person> list = Lists.newArrayList(new Person("lhx", 22), new Person("zl", 20));

        // 得到以name为key,Person为值的一个map
        ImmutableMap<String, Person> uniqueIndex = Maps.uniqueIndex(list, p -> p.name);
        System.out.println(uniqueIndex);//{lhx=Person{name='lhx', age=22}, zl=Person{name='zl', age=20}}

        list.add(new Person("lhx", 32));
        // 报错 索引不唯一
        //ImmutableMap<String, Person> uniqueIndex2 = Maps.uniqueIndex(list, p -> p.name);
        //System.out.println(uniqueIndex2);
    }

如果索引值不是独一无二的,请参见下面的Multimaps.index方法。

difference

Maps.difference(Map, Map)用来比较两个Map以获取所有不同点。该方法返回MapDifference对象,把不同点的维恩图分解为:

entriesInCommon() 两个Map中都有的映射项,包括匹配的键与值
entriesDiffering() 键相同但是值不同值映射项。返回的Map的值类型为MapDifference.ValueDifference,以表示左右两个不同的值
entriesOnlyOnLeft() 键只存在于左边Map的映射项
entriesOnlyOnRight() 键只存在于右边Map的映射项
示例:
    @Test
    public void testMapsdifference() {
        Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
        Map<String, Integer> right = ImmutableMap.of("a", 1, "b", 3, "e", 5);

        MapDifference<String, Integer> diff = Maps.difference(left, right);


        Map<String, Integer> stringIntegerMap;
        //两个Map中都有的映射项,包括匹配的键与值
        stringIntegerMap = diff.entriesInCommon();
        System.out.println(stringIntegerMap);//{a=1}

        //键相同但是值不同值映射项。
        Map<String, MapDifference.ValueDifference<Integer>> differing = diff.entriesDiffering();
        System.out.println(differing);//{b=(2, 3)}

        //键只存在于左边Map的映射项
        stringIntegerMap = diff.entriesOnlyOnLeft();
        System.out.println(stringIntegerMap);//{c=3}

        //键只存在于右边Map的映射项
        stringIntegerMap = diff.entriesOnlyOnRight();
        System.out.println(stringIntegerMap);//{e=5}

    }

处理BiMap的工具方法

Guava中处理BiMap的工具方法在Maps类中,因为BiMap也是一种Map实现。

BiMap工具方法 相应的Map工具方法
synchronizedBiMap(BiMap) Collections.synchronizedMap(Map)
unmodifiableBiMap(BiMap) Collections.unmodifiableMap(Map)

2.5、工具类-Multisets、Multimaps、Tables

Multisets方法
方法 说明 Collection方法的区别
containsOccurrences(Multiset   sup, Multiset sub) 对任意o,如果sub.count(o)<=super.count(o),返回true Collection.containsAll忽略个数,而只关心sub的元素是否都在super中
removeOccurrences(Multiset   removeFrom, Multiset toRemove) 对toRemove中的重复元素,仅在removeFrom中删除相同个数。 Collection.removeAll移除所有出现在toRemove的元素
retainOccurrences(Multiset   removeFrom, Multiset toRetain) 修改removeFrom,以保证任意o都符合removeFrom.count(o)<=toRetain.count(o) Collection.retainAll保留所有出现在toRetain的元素
intersection(Multiset,   Multiset) 返回两个multiset的交集; 没有类似方法
 

Multisets中的其他工具方法还包括:

copyHighestCountFirst(Multiset) 返回Multiset的不可变拷贝,并将元素按重复出现的次数做降序排列
unmodifiableMultiset(Multiset) 返回Multiset的只读视图
unmodifiableSortedMultiset(SortedMultiset) 返回SortedMultiset的只读视图
Multimaps,Tables类似可以自行参看
 
 
 
 
 
posted @ 2019-09-25 16:45  bjlhx15  阅读(746)  评论(0编辑  收藏  举报
Copyright ©2011~2020 JD-李宏旭