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

article/2025/8/23 19:57:08

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/guavaicon-default.png?t=M0H8https://github.com/google/guava

使用

        依赖引入

    <dependencies><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.1-jre</version></dependency></dependencies>

 Guava 集合工具类

Lists

        官网文档:

Lists (Guava: Google Core Libraries for Java 27.0.1-jre API)icon-default.png?t=M0H8https://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 Listsextends Object

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

newArrayList()
newArrayList(E... elements)
newArrayList(Iterable<? extends E> elements)
newArrayList(Iterator<? extends E> elements)

 测试

        ArrayList<Object> objects = Lists.newArrayList();objects.add("张三");objects.add(20);System.out.println("--- newArrayList test ---");System.out.println(objects);System.out.println("--- newArrayList test ---");ArrayList<Object> objects1 = Lists.newArrayList(objects);System.out.println(objects1);System.out.println("--- newArrayList test ---");ArrayList<String> strings = Lists.newArrayList("张三", "北京市海淀区");System.out.println(strings);

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

newArrayListWithCapacity(int initialArraySize)
newArrayListWithExpectedSize(int estimatedSize)
        //如果你事先知道元素的个数,可以用 newArrayListWithCapacity 函数;如果你不能确定元素的个数,可以用newArrayListWithExpectedSize函数//这个方法就是直接返回一个10的数组。ArrayList<Object> objects = Lists.newArrayListWithCapacity(10);objects.add("123");System.out.println(objects);ArrayList<Object> 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 itreturn Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}

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

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

newLinkedList()
newLinkedList(Iterable<? extends E> elements)   
newCopyOnWriteArrayList()
newCopyOnWriteArrayList(Iterable<? extends E> elements)
       /* newLinkedList()newLinkedList(Iterable<? extends E> elements)   newCopyOnWriteArrayList()newCopyOnWriteArrayList(Iterable<? extends E> elements) */LinkedList<Object> objects = Lists.newLinkedList();objects.add("张三");objects.add("李四");System.out.println("--- newLinkedList ---");System.out.println(objects);ArrayList<Object> objects1 = Lists.newArrayList(objects);System.out.println("--- newLinkedList ---");System.out.println(objects1);System.out.println("--- newCopyOnWriteArrayList ---");CopyOnWriteArrayList<Object> objects2 = Lists.newCopyOnWriteArrayList();objects2.add("王五");objects2.add("张三");System.out.println(objects2);System.out.println("--- newCopyOnWriteArrayList ---");CopyOnWriteArrayList<Object> 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<String> strings = Lists.asList(str, strs);System.out.println(strings);

 

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

public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function)

        Function<String, Integer> strlen = new Function<String, Integer>() {public Integer apply(String from) {Preconditions.checkNotNull(from);return from.length();}};List<String> from = Lists.newArrayList("abc", "defg", "hijkl");List<Integer> to = Lists.transform(from, strlen);for (int i = 0; i < from.size(); i++) {System.out.printf("%s has length %d\n", from.get(i), to.get(i));}

 

 

Maps

        官方文档

Maps (Guava: Google Core Libraries for Java 27.0.1-jre API)icon-default.png?t=M0H8https://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 Mapsextends Object
newHashMap
newHashMapWithExpectedSize
newLinkedHashMap 
ImmutableMap
difference
transformValues

测试

newHashMap

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

 newHashMapWithExpectedSize

        Map<Integer, Integer> 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<Integer, Integer> map = Maps.newLinkedHashMap();map.put(11, 11);System.out.println("map:" + map);LinkedHashMap<Integer, Integer> map1 = Maps.newLinkedHashMap(map);System.out.println("map1:" + map1);

 

 ImmutableMap

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

 

difference

        Map<Integer, Integer> map = Maps.newHashMap();map.put(10, 10);Map<Integer, Integer> map1 = Maps.newHashMap();map1.put(10, 10);map1.put(20, 20);MapDifference<Integer, Integer> 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<String, Boolean> fromMap = Maps.newHashMap();fromMap.put("key", true);fromMap.put("value", false);// 对传入的元素取反System.out.println(Maps.transformValues(fromMap, (Function<Boolean, Object>) input -> !input));// value为假,则key变大写Maps.EntryTransformer<String, Boolean, String> 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)icon-default.png?t=M0H8https://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 Setsextends Object
newHashSet
filter
difference
symmetricDifference
intersection
union
cartesianProduct
powerSet

newHashSet

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

 

filter

    /*** filter:返回传入Set集合unfiltered中满足给定Predicate的元素集合Set*/@Testpublic void testFilter() {Set<String> set = Sets.newHashSet("i like u", "i miss u", "i love u");Predicate<String> predicate = new Predicate<String>() {@Overridepublic 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

    /*** difference:返回两个set集合的差的不可修改SetView* A,B是两个集合,则所有属于A且不属于B的元素构成的集合,叫做A与B的差集*/@Testpublic void testDifference() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.difference(set1, set2));        // [2, 4]}

 

symmetricDifference

    /*** symmetricDifference:返回两个set集合的对称差的不可修改SetView* 对称差,即两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合*/@Testpublic void testSymmetricDifference() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]}

 

intersection

    /*** intersection:返回两个set集合的交集的不可修改SetView* 两个集合A和集合B的交集是指含有所有既属于A又属于B的元素,而没有其他元素的集合*/@Testpublic void testIntersection() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]}

Union

    /*** Union:返回两个set集合的并集的不可修改SetView* 若A和B是集合,则A和B并集是有所有A的元素和所有B的元素,而没有其他元素的集合*/@Testpublic void testUnion() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]}

 cartesianProduct

    /*** cartesianProduct:返回通过从各给定集中选择一个元素所形成每一个可能的集合*/@Testpublic void testCartesianProduct() {Set<String> set1 = Sets.newHashSet("i love u", "i hate u");Set<String> set2 = Sets.newHashSet("tom", "jerry");Set<List<String>> 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

    /*** powerSet:返回一个set,包含给定set的所有可能父级集合*/@Testpublic void testPowerSet() {Set<String> set1 = Sets.newHashSet("A", "B", "C");Set<Set<String>> sets = Sets.powerSet(set1);
//        for (Set<String> 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 {/*** filter:返回传入Set集合unfiltered中满足给定Predicate的元素集合Set*/@Testpublic void testFilter() {Set<String> set = Sets.newHashSet("i like u", "i miss u", "i love u");Predicate<String> predicate = new Predicate<String>() {@Overridepublic 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:返回两个set集合的差的不可修改SetView* A,B是两个集合,则所有属于A且不属于B的元素构成的集合,叫做A与B的差集*/@Testpublic void testDifference() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.difference(set1, set2));        // [2, 4]}/*** symmetricDifference:返回两个set集合的对称差的不可修改SetView* 对称差,即两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合*/@Testpublic void testSymmetricDifference() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]}/*** intersection:返回两个set集合的交集的不可修改SetView* 两个集合A和集合B的交集是指含有所有既属于A又属于B的元素,而没有其他元素的集合*/@Testpublic void testIntersection() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]}/*** Union:返回两个set集合的并集的不可修改SetView* 若A和B是集合,则A和B并集是有所有A的元素和所有B的元素,而没有其他元素的集合*/@Testpublic void testUnion() {Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]}/*** cartesianProduct:返回通过从各给定集中选择一个元素所形成每一个可能的集合*/@Testpublic void testCartesianProduct() {Set<String> set1 = Sets.newHashSet("i love u", "i hate u");Set<String> set2 = Sets.newHashSet("tom", "jerry");Set<List<String>> 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:返回一个set,包含给定set的所有可能父级集合*/@Testpublic void testPowerSet() {Set<String> set1 = Sets.newHashSet("A", "B", "C");Set<Set<String>> sets = Sets.powerSet(set1);
//        for (Set<String> 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]]}}

http://chatgpt.dhexx.cn/article/DcQAYq5q.shtml

相关文章

Java常用工具类 : StringUtils、CollectionUtils、ArrayUtils、Lists、Maps等

文章目录 StringUtils引入依赖判断函数 (isNotBlank系列)大小写函数 (转换)删除函数 (remove)字符替换函数 (replace)拆分合并函数 (split)截取函数 (substring)删除空白函数 (trim)判断是否相等函数 (equals)是否包含函数 (contains) CollectionUtils集合判断函数并集、交集、…

Lists的使用

List&#xff08;接口&#xff09;顺序时List最重要的特性&#xff1a;它可保证元素按照规定的顺序排列。List为Collection添加了大量方法&#xff0c;以便我们在List中部插入和删除元素&#xff08;只推荐对LinkedList这样做&#xff09;。List也会生成一个ListIterator&#…

Lists 方法汇总

一、Lists.partition(List<T> list, int size) 将 list 集合按指定长度进行切分&#xff0c;返回新的List<List<T>>集合。 import com.google.common.collect.Lists; import org.junit.Test; import java.util.List;public class ListDemo {Testpublic voi…

LU分解的实现

LU分解是将矩阵分解为一个下三角矩阵和一个上三角矩阵的乘积。矩阵可以不是NxN的矩阵 一个可逆矩阵可以进行LU分解当且仅当它的所有子式都非零。如果要求其中的L矩阵&#xff08;或U矩阵&#xff09;为单位三角矩阵&#xff0c;那么分解是唯一的。同理可知&#xff0c;矩阵的L…

LU分解求线性方程组的解

LU分解是矩阵分解的一种&#xff0c;可以将一个矩阵分解为一个上三角矩阵和一个下三角矩阵的乘积。 LU分解可以用来求逆矩阵&#xff0c;解线性方程组等。本文将介绍LU分解求线性方程组的解。 1.定义 如果A是一个方阵&#xff0c;A的LU分解是将A分解成如下形式: 其中L,U分别为…

矩阵分析——LU分解

LU分解初步 矩阵的LU分解主要用来求解线性方程组或者计算行列式。在使用初等行变换法求解线性方程组的过程中&#xff0c;系数矩阵的变化情况如下&#xff1a; 由上可知&#xff1a; &#xff0c;其中U就是上面矩阵A经过行变换后的上三角矩阵&#xff0c;Eij表示将i行元素与j行…

Doolittle分解法(LU分解)详细分析以及matlab的实现

一、基本介绍 前面介绍的Gauss消去法实际上做的事情是将系数矩阵A做了一个三角分解&#xff0c;即&#xff1a; ALU 式&#xff08;1&#xff09; 其中&#xff0c;L为单位下三角阵&#xff0c;U为上三角阵&#xff0c;该分解唯一。若A为非奇异&#xff0c;则U也非奇异。…

线性代数笔记10——矩阵的LU分解

在线性代数中&#xff0c; LU分解(LU Decomposition)是矩阵分解的一种&#xff0c;可以将一个矩阵分解为一个单位下三角矩阵和一个上三角矩阵的乘积&#xff08;有时是它们和一个置换矩阵的乘积&#xff09;。LU分解主要应用在数值分析中&#xff0c;用来解线性方程、求反矩阵或…

线性代数——LU(LR)分解

文章目录 定义为什么要LU分解为什么能做到LU分解 利用LU分解求行列式值利用LU分解求解线性方程组利用LU分解求逆矩阵对角线上元素有0的情况 定义 定义&#xff1a;给定矩阵A&#xff0c;将A表示成下三角矩阵L和上三角矩阵U的乘积&#xff0c;称为LU分解。再进一步&#xff0c;…

LU分解Matlab算法分析

最近矩阵分析老师出了一道题目作为作业&#xff0c;是一道程序题&#xff0c;题目是对A矩阵做LU分解&#xff0c;要求能对A实现PALU的分解&#xff0c;并最终输出L&#xff0c;U&#xff0c;P矩阵。 先来解读下题目&#xff0c;寥寥几句话&#xff0c;里面囊括的信息量却不少&a…

LU分解,LDLT分解,Cholesky分解

LU分解 如果方阵是非奇异的&#xff0c;即的行列式不为0&#xff0c;LU分解总是存在的。 ALU&#xff0c;将系数矩阵A转变成等价的两个矩阵L和U的乘积&#xff0c;其中L和U分别是下三角和上三角矩阵&#xff0c;而且要求L的对角元素都是1&#xff0c;形式如下&#xff1a; 本…

矩阵的直接LU分解法

上篇博文由高斯消去法的矩阵形式推出了矩阵的LU分解&#xff1a;矩阵的三角分解法&#xff1b; 实际上&#xff0c;可以直接处理矩阵&#xff0c;得到矩阵的LU分解&#xff0c;这就是矩阵的直接LU分解&#xff1b;直接通过矩阵的元素得到计算LU元素的递推公式&#xff0c;不需…

LU分解、LDLT分解和Cholesky分解

LU分解 概念&#xff1a;假定我们能把矩阵A写成下列两个矩阵相乘的形式&#xff1a;ALU&#xff0c;其中L为下三角矩阵&#xff0c;U为上三角矩阵。这样我们可以把线性方程组Ax b写成 Ax (LU)x L(Ux) b。令Ux y&#xff0c;则原线性方程组Ax b可首先求解向量y 使Ly b&am…

A的LU分解

前面我们曾经通过高斯消元将矩阵A最终转化成了上三角阵U&#xff0c;那么今天我们就继续深入探索A和U之间到底有什么样的联系。在开始之前&#xff0c;先交代一些需用到的基础理论。假设A是可逆阵&#xff0c;则有AA-1I&#xff0c;两边同时转置&#xff0c;根据乘积的转置等于…

LU分解(matlab实现)

LU分解(LU Decomposition)是矩阵分解的一种&#xff0c;可以将一个矩阵分解为一个下三角矩阵和一个上三角矩阵的乘积。 主要的算法思路是从下至上地对矩阵A做初等行变换&#xff0c;将对角线左下方的元素变成零&#xff0c;这些行变换的效果等同于左乘一系列单位下三角矩阵&…

矩阵的LU分解,LU分解的推广,LU分解有什么意义,为什么要用LU分解。

一点点数学&#xff01;开干&#xff01; 参考书籍&#xff1a;《矩阵分析与计算》李继根 张新发编著 矩阵的LU分解&#xff1a; LU分解定理&#xff1a;如果n阶方阵A的各阶顺序主子式≠0&#xff08;K1、2、3&#xff0c;…&#xff0c;n&#xff09;&#xff0c;即A的各阶…

LU分解(图解)

三角分解(LU分解) 在线性代数中&#xff0c; LU分解(LU Decomposition)是矩阵分解的一种&#xff0c;可以将一个矩阵分解为一个单位下三角矩阵和一个上三角矩阵的乘积&#xff08;有时是它们和一个置换矩阵的乘积&#xff09;。LU分解主要应用在数值分析中&#xff0c;用来解线…

矩阵系列:LU分解

1矩阵LU分解模块 1.1 LU分解数学表达 首先要明确的是&#xff0c;矩阵的LU分解是有局限性的&#xff0c;即LU分解只针对非奇异矩阵。那么什么是非奇异矩阵呢&#xff1f;即各阶顺序主子式不为零。 &#xff08;1&#xff09;高斯消去法 LU分解的思想来源于高斯消去法&#xff…

LU分解(图解与应用举例)

三角分解(LU分解) 在线性代数中&#xff0c; LU分解(LU Decomposition)是矩阵分解的一种&#xff0c;可以将一个矩阵分解为一个单位下三角矩阵和一个上三角矩阵的乘积&#xff08;有时是它们和一个置换矩阵的乘积&#xff09;。LU分解主要应用在数值分析中&#xff0c;用来解线…

矩阵分解入门——LU分解

文章目录 LU分解LU分解简介LU分解与高斯分解的对比LU的主要用途使用LU矩阵的注意事项初等矩阵与消元LU分解与配方法实际效果对比(matlab)使用LU分解中的一些特例 A A A矩阵中主元&#xff08;位于第一行第一列的元素&#xff09;为0LU分解后 U U U为非满秩 LU分解的推广1——LD…