当前位置: 首页 > article >正文

guava里常用功能

guava 是 Google 提供的一个 Java 库,提供了很多实用的工具类和方法,可以帮助开发者更高效地编写代码。以下是一些常用的 Guava 工具类及其功能示例:

1. Lists

用于操作列表的工具类。

import com.google.common.collect.Lists;

List<Integer> numbers = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitions = Lists.partition(numbers, 2);
// partitions: [[1, 2], [3, 4], [5]]

2. Maps

用于操作映射的工具类。

import com.google.common.collect.Maps;

Map<String, Integer> map = Maps.newHashMap();
map.put("apple", 1);
map.put("banana", 2);
Map<String, Integer> immutableMap = Maps.immutableEnumMap(map);
// 创建不可变的映射

3. Sets

用于操作集合的工具类。

import com.google.common.collect.Sets;

Set<String> set1 = Sets.newHashSet("a", "b", "c");
Set<String> set2 = Sets.newHashSet("b", "c", "d");
Set<String> union = Sets.union(set1, set2);
// union: [a, b, c, d]

4. Optional

用于处理可能为空的值。

import com.google.common.base.Optional;

Optional<String> optional = Optional.fromNullable(null);
if (optional.isPresent()) {
    System.out.println(optional.get());
} else {
    System.out.println("值为空");
}

5. Strings

字符串操作的工具类。

import com.google.common.base.Strings;

String str = "Hello, World!";
String padded = Strings.padStart(str, 20, '*');
// padded: "*******Hello, World!"

6. Joiner

用于连接字符串的工具类。

import com.google.common.base.Joiner;

List<String> list = Arrays.asList("a", "b", "c");
String joined = Joiner.on(", ").join(list);
// joined: "a, b, c"

7. Splitter

用于分割字符串的工具类。

import com.google.common.base.Splitter;

String csv = "apple, banana, cherry";
Iterable<String> fruits = Splitter.on(", ").split(csv);
// fruits: ["apple", "banana", "cherry"]

8. Preconditions

用于参数检查的工具类。

import com.google.common.base.Preconditions;

public void setAge(int age) {
    Preconditions.checkArgument(age > 0, "年龄必须大于0");
    // 其他逻辑
}

9. Functional Programming

Guava 还支持函数式编程风格。

import com.google.common.base.Function;
import com.google.common.collect.Lists;

List<String> names = Lists.newArrayList("Alice", "Bob", "Charlie");
List<Integer> nameLengths = Lists.transform(names, new Function<String, Integer>() {
    @Override
    public Integer apply(String name) {
        return name.length();
    }
});
// nameLengths: [5, 3, 7]

10.Immutable:不可变对象工具类

import com.google.common.base.ImmutableList;
import com.google.common.base.ImmutableMap;

public class ImmutableExample {
    public static void main(String[] args) {
        // 创建一个不可变列表
        ImmutableList<String> immutableList = ImmutableList.of("apple", "banana", "cherry");

        // 创建一个不可变映射
        ImmutableMap<String, String> immutableMap = ImmutableMap.of(
                "key1", "value1",
                "key2", "value2"
        );

        // 打印不可变对象
        System.out.println(immutableList);
        System.out.println(immutableMap);
    }
}

11.Cache:缓存工具类

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class CacheExample {
    public static void main(String[] args) {
        // 创建一个缓存,设置缓存的大小为 10 个元素,缓存的过期时间为 10 秒
        LoadingCache<String, String> cache = CacheBuilder.newBuilder()
              .maximumSize(10)
              .expireAfterWrite(10, TimeUnit.SECONDS)
              .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        // 从数据库或其他数据源中加载数据
                        return "Value for " + key;
                    }
                });

        // 向缓存中添加元素
        cache.put("key1", "value1");
        cache.put("key2", "value2");

        // 获取缓存中的元素
        String value1 = cache.get("key1");
        String value2 = cache.get("key2");

        // 打印缓存中的元素
        System.out.println("Value for key1: " + value1);
        System.out.println("Value for key2: " + value2);
    }
}

以上只是 Guava 提供的一部分功能,实际上这个库还有很多其他强大的工具类,能帮助你更高效地处理集合、字符串、并发等问题。你可以根据具体需求查阅 Guava 的官方文档 以获取更多信息。


http://www.kler.cn/news/336719.html

相关文章:

  • 强化学习笔记之【Q-learning算法和DQN算法】
  • 区块链的编程语言有那些?
  • 基于STM32的智能垃圾桶控制系统设计
  • wordpress父分类和归档页调用子分类名称和链接
  • can 总线入门———can简介硬件电路
  • html+css+js实现Collapse 折叠面板
  • [运维]5.镜像本地存在但仍然从网络拉取的问题
  • Qt 6 相比 Qt 5 的主要提升与更新
  • Java基础-单例模式的实现
  • Android Codec2 CCodec(十六)C2AllocatorGralloc
  • 241006-Gradio中Chatbot通过CSS自适应调整高度
  • 黑名单与ip禁令是同一个东西吗
  • CSS中的class与id
  • VirtulBOX Ubuntu22安装dpdk23.11
  • 计算机网络——p2p
  • Prometheus监控MySQL主从数据库
  • simple c++ 无锁队列
  • Mybatis测试案例
  • 什么是 Angular 的 @HostBinding 注解
  • VMware Tools 安装和配置