Guava:一款强大的Java库,让你的开发更高效

Guava是一款由Google开源的Java库,提供了丰富的工具类和扩展类,帮助我们解决日常开发中遇到的各种问题。

本文将详细介绍Guava库的特点、常用工具类及其使用方法,让小白读者轻松上手。

1、Guava简介

Guava是一款由Google开源的Java库,旨在为Java开发者提供一系列便捷的工具类和扩展类,以提高开发效率。

Guava包含了很多实用的工具类,如集合类(multisetsmultimapstables等)、数式编程风格(通过supplierfunctionpredicateoptional等实现)、缓存(CacheLoaderCacheBuilder等)、支持原生的Java类型、事件总线以及并发库扩展等,可以帮助我们轻松应对日常开发中的各种挑战。

2、Guava的安装与使用

1.添加依赖

要使用Guava库,需要在项目中添加其依赖。如果你使用Maven进行项目管理,可以在pom.xml文件中添加以下依赖:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>31.0.1-jre</version> <!-- 请根据实际版本进行替换 -->
</dependency>

如果你使用Gradle,可以在build.gradle文件中添加以下依赖:

dependencies {
  implementation 'com.google.guava:guava:31.0.1-jre' // 请根据实际版本进行替换
}

2.使用Guava工具类

Guava提供了很多实用的工具类,下面将介绍几个常用的工具类及其使用方法。

(1).增强java集合功能

Guava库向我们提供了一些更加丰富的集合类,比如诸如ImmutableSetImmutableListImmutableSortedSetImmutableMap以及更为泛化和强大的Multiset(可以存储相同元素的集合)、BiMap(可以将两个键映射到一个值)、Table(可以将一个键映射到另一个键的值)等。

(2).字符串处理

Guava库提供了Joiner和Splitter类,可以简化多个字符串之间的拼接与分割。

(3).函数式编程

Guava 还提供了许多函数式编程的类,比如Function(将一个值转换为另一个值)、Predicate(判断一个值是否满足某个条件)、Consumer(消费一个值)等。

  • 增强java集合功能、字符串处理、函数式编程使用示例:
import com.google.common.collect.*;

public class GuavaExample {

    public static void main(String[] args) {

        // 创建一个 Multiset
        Multiset<String> words = HashMultiset.create();
        words.add("Hello");
        words.add("World");
        words.add("Hello");

        // 统计每个单词出现的次数
        System.out.println(words.count("Hello")); // 2
        System.out.println(words.count("World")); // 1

        // 创建一个 BiMap
        BiMap<String, Integer> nameToAge = HashBiMap.create();
        nameToAge.put("John", 20);
        nameToAge.put("Jane", 21);

        // 获取 John 的年龄
        System.out.println(nameToAge.get("John")); // 20

        // 创建一个 Table
        Table<String, Integer, String> studentToGrade = HashBasedTable.create();
        studentToGrade.put("John", 100, "A");
        studentToGrade.put("Jane", 90, "B");

        // 获取 John 的成绩
        System.out.println(studentToGrade.get("John", 100)); // A

        // 字符串处理
        Joiner joiner = Joiner.on(",").skipNulls();
        System.out.println(joiner.join("Harry", null, "Ron", "Hermione"));   //返回 "Harry,Ron,Hermione"

        // 使用 Function 将字符串转换为 Integer
        Function<String, Integer> toInteger = Integer::parseInt;
        System.out.println(toInteger.apply("100")); // 100

        // 使用 Predicate 判断字符串是否是数字
        Predicate<String> isNumber = s -> s.matches("\\d+");
        System.out.println(isNumber.test("100")); // true

        // 使用 Consumer 消费一个值
        Consumer<Integer> printInteger = i -> System.out.println(i);
        printInteger.accept(100); // 100
    }
}

(4).集合操作

Guava的集合操作工具类主要包括:Lists、Sets、Maps等。这些工具类提供了很多便捷的方法,如排序、过滤、转换等。

  • 示例:使用Lists工具类对列表进行排序和过滤。
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
public class ListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("orange");
        list.add("grape");
        // 排序
        List<String> sortedList = Lists.newArrayList(list).sort().immutableList();
        System.out.println("Sorted List: " + sortedList);
        // 过滤
        List<String> filteredList = Lists.newArrayList(list).filter(s -> s.startsWith("a")).immutableList();
        System.out.println("Filtered List: " + filteredList);
    }
}

(5).缓存

Guava的缓存工具类是Cache,它提供了便捷的缓存实现,同时支持自定义的缓存策略。

  • 示例:使用Cache进行缓存操作。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class CacheExample {
    public static void main(String[] args) {
        Cache<String, String> cache = CacheBuilder.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build();
        // 添加缓存
        cache.put("key1", "value1");
        cache.put("key2", "value2");
        // 获取缓存
        String value1 = cache.getIfPresent("key1");
        System.out.println("Value for key1: " + value1);
        // 删除缓存
        cache.remove("key1");
        // 检查缓存是否存在
        boolean exists = cache.exists("key1");
        System.out.println("Exists key1: " + exists);
    }
}

(6).Primitives support(原生类型支持)

Guava库提供了对Java原生类型(如int、long、double等)的支持,这使得在集合操作中可以直接使用这些类型,而无需包装成对应的包装类(如Integer、Long等)。这有助于提高性能,尤其是在处理大量数据时。

  • 示例:使用Guava的Ints工具类进行原生类型操作。
import com.google.common.collect.Ints;
public class PrimitivesSupportExample {
    public static void main(String[] args) {
        // 创建一个整数列表
        int[] numbers = {1, 2, 3, 4, 5};
        // 使用Guava的Ints工具类进行操作
        int sum = Ints.sum(numbers);
        System.out.println("Sum: " + sum);
        int product = Ints.product(numbers);
        System.out.println("Product: " + product);
        // 对列表进行排序
        int[] sortedNumbers = Ints排序(numbers);
        System.out.println("Sorted Numbers: " + Arrays.toString(sortedNumbers));
    }
}

(7).Common annotations(通用注解)

Guava提供了一些常用的注解,如@Nullable@NonNull@VisibleForTesting等,这些注解可以帮助开发者更好地理解代码的意图,并提高代码的可维护性。

  • 示例:使用Guava的注解来标记方法的预期行为。
import com.google.common.base.Preconditions;
public class AnnotationsExample {
    public static void main(String[] args) {
        // 使用@NonNull注解来标记一个不应该为null的参数
        @NonNull String input = "Hello, Guava!";
        Preconditions.checkNotNull(input, "Input cannot be null");
        // 使用@Nullable注解来标记一个可能为null的参数
        @Nullable String optionalInput = null;
        Preconditions.checkArgument(optionalInput != null || "Default value", "Input is required");
        // 使用@VisibleForTesting注解来标记一个仅用于测试的方法
        @VisibleForTesting static void testMethod() {
            System.out.println("This method is only visible for testing");
        }
    }
}

(8).并发库扩展

Guava对Java的并发库进行了扩展,提供了许多便利的并发工具类,如CountDownLatchCyclicBarrierSemaphore等,这些工具类可以帮助开发者更容易地实现并发编程。

  • 示例:使用Guava的CountDownLatch来同步多个线程。
import com.google.common.util.concurrent.CountDownLatch;
public class ConcurrencyExample {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(() -> {
            try {
                System.out.println("Thread 1 is waiting");
                Thread.sleep(1000);
                System.out.println("Thread 1 is done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }).start();
        new Thread(() -> {
            try {
                System.out.println("Thread 2 is waiting");
                Thread.sleep(2000);
                System.out.println("Thread 2 is done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }).start();
        new Thread(() -> {
            try {
                System.out.println("Thread 3 is waiting");
                Thread.sleep(3000);
                System.out.println("Thread 3 is done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }).start();
        try {
            latch.await();
            System.out.println("All threads are done");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Guava库是一个功能强大的Java库,它提供了丰富的工具类和扩展类,可以帮助开发者更高效地完成日常开发任务。

从集合操作到并发编程,从原生类型支持到注解工具,Guava库都有涉猎。

本文简单地介绍,希望你能够对Guava库有一个基本的了解,并能够在实际项目中应用这些工具类,提高代码的质量和开发效率。

Guava库的功能非常广泛,本文只是介绍了其中的一部分。

要完全掌握Guava库的所有功能,还需要深入学习和实践。

建议你阅读Guava的官方文档,以获取更全面和深入的了解。