栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Google guava工具类中Lists、Maps、Sets简单使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Google guava工具类中Lists、Maps、Sets简单使用

Google guava

Guava是对Java API的补充,对Java开发中常用功能进行更优雅的实现,使得编码更加轻松,代码容易理解。Guava使用了多种设计模式,同时经过了很多测试,得到了越来越多开发团队的青睐。Java最新版本的API采纳了Guava的部分功能,但依旧无法替代。

特点

高效设计良好的API,被Google的开发者设计,实现和使用遵循高效的java语法实践使代码更刻度,简洁,简单节约时间,资源,提高生产力  Guava工程包含了若干被Google的 Java项目广泛依赖的核心库

核心库例如:

集合 [collections]缓存 [caching]原生类型支持 [primitives support]并发库 [concurrency libraries]通用注解 [common annotations]字符串处理 [string processing]I/O 等等。         github地址

https://github.com/google/guavahttps://github.com/google/guava

使用         依赖引入
    
        
            com.google.guava
            guava
            28.1-jre
        
    
 Guava 集合工具类 Lists

        官网文档:

Lists (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Lists.html对应于List集合接口, 在com.google.common.collect包下

 Lists 接口的声明如下:

@GwtCompatible(emulated=true)
public final class Lists
    extends Object

 Lists 类主要提供了对List类的子类构造以及操作的静态方法。在Lists类中支持构造 ArrayList、linkedList 以及 newCopyOnWriteArrayList 对象的方法。其中提供了以下构造ArrayList的函数:下面四个构造一个 ArrayList 对象,但是不显式的给出申请空间的大小:

newArrayList()
newArrayList(E... elements)
newArrayList(Iterable elements)
newArrayList(Iterator elements)
 测试
        ArrayList objects = Lists.newArrayList();
        objects.add("张三");
        objects.add(20);
        System.out.println("--- newArrayList test ---");
        System.out.println(objects);
        System.out.println("--- newArrayList test ---");
        ArrayList objects1 = Lists.newArrayList(objects);
        System.out.println(objects1);
        System.out.println("--- newArrayList test ---");
        ArrayList strings = Lists.newArrayList("张三", "北京市海淀区");
        System.out.println(strings); 

以下两个函数在构造 ArrayList 对象的时候给出了需要分配空间的大小:

newArrayListWithCapacity(int initialArraySize)
newArrayListWithExpectedSize(int estimatedSize)
        //如果你事先知道元素的个数,可以用 newArrayListWithCapacity 函数;如果你不能确定元素的个数,可以用newArrayListWithExpectedSize函数
        //这个方法就是直接返回一个10的数组。
        ArrayList objects = Lists.newArrayListWithCapacity(10);
        objects.add("123");
        System.out.println(objects);
        ArrayList objects1 = Lists.newArrayListWithExpectedSize(10);
        objects1.add("123");
        System.out.println(objects1); 

在 newArrayListWithExpectedSize 函数里面调用了 computeArrayListCapacity(int arraySize) 函数,其实现如下:

@VisibleForTesting 
static int computeArrayListCapacity(int arraySize) {
    checkArgument(arraySize >= 0);
   
  // TODO(kevinb): Figure out the right behavior, and document it
    return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}

         返回的容量大小为 5L + arraySize + (arraySize / 10),当 arraySize 比较大的时候,给定大小和真正分配的容量之比为 10/11。

Lists 类还支持构造 linkedList、newCopyOnWriteArrayList 对象,其函数接口为:

newlinkedList()
newlinkedList(Iterable elements)   
newCopyonWriteArrayList()
newCopyonWriteArrayList(Iterable elements)
       
        linkedList objects = Lists.newlinkedList();
        objects.add("张三");
        objects.add("李四");
        System.out.println("--- newlinkedList ---");
        System.out.println(objects);
        ArrayList objects1 = Lists.newArrayList(objects);
        System.out.println("--- newlinkedList ---");
        System.out.println(objects1);
        System.out.println("--- newCopyonWriteArrayList ---");
        CopyOnWriteArrayList objects2 = Lists.newCopyonWriteArrayList();
        objects2.add("王五");
        objects2.add("张三");
        System.out.println(objects2);
        System.out.println("--- newCopyonWriteArrayList ---");
        CopyOnWriteArrayList objects3 = Lists.newCopyonWriteArrayList(objects2);
        System.out.println(objects3); 

 

我们还可以将两个(或三个)类型相同的数据存放在一个list中,这样可以传入到只有一个参数的函数或者需要减少参数的函数中,这些函数如下:

asList(@Nullable E first, E[] rest)
asList(@Nullable E first, @Nullable E second, E[] rest)
        String str = "i love u";
        String[] strs = {"i like u", "i miss u"};
        List strings = Lists.asList(str, strs);
        System.out.println(strings);

 

 Lists 类中 transform 函数可以根据传进来的 function 对 fromList 进行相应的处理,并将处理得到的结果存入到新的list对象中,这样有利于我们进行分析,函数接口如下:

public static  List transform(List fromList, Function function)

        Function strlen = new Function() {
            public Integer apply(String from) {
                Preconditions.checkNotNull(from);
                return from.length();
            }
        };

        List from = Lists.newArrayList("abc", "defg", "hijkl");
        List to = Lists.transform(from, strlen);
        for (int i = 0; i < from.size(); i++) {
            System.out.printf("%s has length %dn", from.get(i), to.get(i));
        }

 

 

Maps

        官方文档

Maps (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Maps.html com.google.common.collect.Maps 接口的声明:

@GwtCompatible(emulated=true)
public final class Maps
    extends Object
newHashMap
newHashMapWithExpectedSize
newlinkedHashMap 
ImmutableMap
difference
transformValues

测试

newHashMap
        HashMap hashMap = Maps.newHashMap();
        for (int i = 0; i < 10; i++) {
            hashMap.put(i, i);
        }
        System.out.println("hashMap:" + hashMap);
        HashMap hashMap1 = Maps.newHashMap(hashMap);
        System.out.println("hashMap1:" + hashMap1);

 newHashMapWithExpectedSize
        Map map = Maps.newHashMapWithExpectedSize(3);
        map.put(1, 1);
        map.put(2, 2);
        map.put(3, 3);
        System.out.println("map:" + map);     // map:{1=1, 2=2, 3=3}

 

 newlinkedHashMap
        Map map = Maps.newlinkedHashMap();
        map.put(11, 11);
        System.out.println("map:" + map);
        linkedHashMap map1 = Maps.newlinkedHashMap(map);
        System.out.println("map1:" + map1);

 

 ImmutableMap
        ImmutableMap a = ImmutableMap.of("a", "1");
        System.out.println(a);

 

difference
        Map map = Maps.newHashMap();
        map.put(10, 10);
        Map map1 = Maps.newHashMap();
        map1.put(10, 10);
        map1.put(20, 20);
        MapDifference difference = Maps.difference(map, map1);
        System.out.println(difference.areEqual());
        System.out.println(difference.entriesInCommon());
        System.out.println(difference.entriesOnlyOnRight());
        System.out.println(difference.entriesOnlyOnLeft());
        System.out.println(difference.entriesDiffering());
        System.out.println(difference);
transformValues
        Map fromMap = Maps.newHashMap();
        fromMap.put("key", true);
        fromMap.put("value", false);
        // 对传入的元素取反
        System.out.println(Maps.transformValues(fromMap, (Function) input -> !input));

        // value为假,则key变大写
        Maps.EntryTransformer entryTransformer = (key, value) -> value ? key : key.toUpperCase();
        System.out.println(Maps.transformEntries(fromMap, entryTransformer));
  Sets           官方文档

Sets (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Sets.htmlcom.google.common.collect.Sets 接口的声明:

@GwtCompatible(emulated=true)
public final class Sets
    extends Object
newHashSet
filter
difference
symmetricDifference
intersection
union
cartesianProduct
powerSet

newHashSet
        HashSet objects = Sets.newHashSet();
        objects.add("张三");
        objects.add("李四");
        System.out.println(objects); 

 

filter
    
    @Test
    public void testFilter() {
        Set set = Sets.newHashSet("i like u", "i miss u", "i love u");
        Predicate predicate = new Predicate() {
            @Override
            public boolean apply(String input) {
                //过滤包含字母l的元素
                return input.contains("l");
            }
        };
        System.out.println(Sets.filter(set, predicate));                        // [i like u, i love u]
        System.out.println(Sets.filter(set, input -> input.contains("l")));     // [i like u, i love u]
    }

difference
    
    @Test
    public void testDifference() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.difference(set1, set2));        // [2, 4]
    }

 

symmetricDifference
    
    @Test
    public void testSymmetricDifference() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]
    }

 

intersection
    
    @Test
    public void testIntersection() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]
    }

Union
    
    @Test
    public void testUnion() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]
    }

 cartesianProduct
    
    @Test
    public void testCartesianProduct() {
        Set set1 = Sets.newHashSet("i love u", "i hate u");
        Set set2 = Sets.newHashSet("tom", "jerry");
        Set> sets = Sets.cartesianProduct(set1, set2);
        System.out.println(sets);       // [[i hate u, tom], [i hate u, jerry], [i love u, tom], [i love u, jerry]]
    }

powerSet
    
    @Test
    public void testPowerSet() {
        Set set1 = Sets.newHashSet("A", "B", "C");
        Set> sets = Sets.powerSet(set1);
//        for (Set set : sets) {
//            System.out.println(set);
//        }
        System.out.println(Arrays.toString(sets.toArray()));    // [[], [A], [B], [A, B], [C], [A, C], [B, C], [A, B, C]]
    }

 完整代码

        maven项目里用junit进行单元测试

import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class TestSets {
    
    @Test
    public void testFilter() {
        Set set = Sets.newHashSet("i like u", "i miss u", "i love u");
        Predicate predicate = new Predicate() {
            @Override
            public boolean apply(String input) {
                //过滤包含字母l的元素
                return input.contains("l");
            }
        };
        System.out.println(Sets.filter(set, predicate));                        // [i like u, i love u]
        System.out.println(Sets.filter(set, input -> input.contains("l")));     // [i like u, i love u]
    }

    
    @Test
    public void testDifference() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.difference(set1, set2));        // [2, 4]
    }

    
    @Test
    public void testSymmetricDifference() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]
    }


    
    @Test
    public void testIntersection() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]
    }

    
    @Test
    public void testUnion() {
        Set set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]
    }

    
    @Test
    public void testCartesianProduct() {
        Set set1 = Sets.newHashSet("i love u", "i hate u");
        Set set2 = Sets.newHashSet("tom", "jerry");
        Set> sets = Sets.cartesianProduct(set1, set2);
        System.out.println(sets);       // [[i hate u, tom], [i hate u, jerry], [i love u, tom], [i love u, jerry]]
    }

    
    @Test
    public void testPowerSet() {
        Set set1 = Sets.newHashSet("A", "B", "C");
        Set> sets = Sets.powerSet(set1);
//        for (Set set : sets) {
//            System.out.println(set);
//        }
        System.out.println(Arrays.toString(sets.toArray()));    // [[], [A], [B], [A, B], [C], [A, C], [B, C], [A, B, C]]
    }

}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号