Recommend the commonly used tool library google guava for Java development

Guava

Guava is a Google open source Java core library, which provides many practical tools and auxiliary classes to make Java development more concise, efficient and reliable. At present and hutooltogether, it is a tool library commonly used in the industry. shigenI also prefer to use it. Here are some commonly used tool libraries and usage cases.

reference:

pom dependencies

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

Map

Table-double key map

The Table interface can be seen as a matrix-like data structure that contains two keys: row keys and column keys. Its main feature is that it can locate and access values ​​​​through two keys, and its type: Table<R,C,V>

basic api

Transformation of ranks

public static <R, C, V> Table<C, R, V> transpose(Table<R, C, V> table) {
    return (Table)(table instanceof Tables.TransposeTable ? ((Tables.TransposeTable)table).original : new Tables.TransposeTable(table));
}

Convert to nested map

Map<String, Map<String, Integer>> rowMap = table.rowMap();
Map<String, Map<String, Integer>> columnMap = table.columnMap();

BiMap-two-way map

Quickly find the key based on the value, so both the key and the value are required to be unique

  • inverseThe original key-value mapping is reversed by the method BiMap, but this reversed object BiMapis not a new object, it implements a view association, so BiMapall operations performed on the reversed one will act on the original one BiMap.
  • Inherit hashMap, key and value cannot be repeated

MultiMap-multi-value map

A key is mapped to multiple values, the bottom layer is Map<String, List>

Create and convert

Multimap<String, String> multiMap = ArrayListMultimap.create();
multiMap.putAll("name", Arrays.asList("shigen", "aaa", "bbb"));
Collection<String> names = multiMap.get("name");
Map<String, Collection<String>> stringCollectionMap = multiMap.asMap();

RangeMap - range map

RangeMapDescribes a mapping relationship from an interval to a specific value, allowing us to write code in a more elegant way

Fractional judgment case

‘com.google.common.collect.RangeMap’ is marked unstable with @Beta

shigenI think this is very useful, and it omits a lot of if-else codes based on interval judgments for us

RangeMap<Integer, String> rangeMap = TreeRangeMap.create();
rangeMap.put(Range.closedOpen(0,60),"fail");
rangeMap.put(Range.closed(60,90),"satisfactory");
rangeMap.put(Range.openClosed(90,100),"excellent");

System.out.println(rangeMap.get(59));
System.out.println(rangeMap.get(60));
System.out.println(rangeMap.get(90));
System.out.println(rangeMap.get(91));

ClassToInstanceMap - Instance Map

Its key is Classand value is the Classcorresponding instance object ( Map<Class, List<Object>). Mandatory type conversion is omitted when taking out the object, avoiding manual type conversion mistakes.

Suitable for caching objects, but don't want to do complex validation

MutableClassToInstanceMap<List> listMutableClassToInstanceMap = MutableClassToInstanceMap.create();
ArrayList<String> strings = new ArrayList<>();
strings.add("1111");
listMutableClassToInstanceMap.putInstance(ArrayList.class, strings);
ArrayList instance = listMutableClassToInstanceMap.getInstance(ArrayList.class);
// true
System.out.println(strings == instance);

Strings

  • isNullOrEmpty(String string): Determine whether the string is empty or null.
  • padEnd(String string, int minLength, char padChar): Pad the specified characters at the end of the string until the string reaches the specified length.
  • padStart(String string, int minLength, char padChar): Pad the specified characters at the beginning of the string until the string reaches the specified length.
  • repeat(String string, int count): Repeat the specified string for the specified number of times.
  • commonPrefix(CharSequence a, CharSequence b): Get the longest common prefix of two strings.
  • commonSuffix(CharSequence a, CharSequence b): Get the longest common suffix of two strings.

This piece is shigenstill used , and it is in line with my code programming habits.hutoolstrUtil

Collections

  1. ImmutableList

Immutable collection is an important feature of Guava, it can ensure that the collection is not modified, thus avoiding the problem of concurrent access

List<String> list = Lists.newArrayList("a", "b", "c");
ImmutableList<String> immutableList = ImmutableList.copyOf(list);
  1. Iterables

Get element API

Get eligible elements

Convert collection type

Condition checking (Preconditions)

Preconditions is a set of precondition checking tools provided by Guava, which provides some methods to check whether the parameters meet expectations.

shigenI think this is assertvery similar to.

The following are the main methods of Preconditions:

  • checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs): Check whether the parameters meet expectations, and throw an IllegalArgumentException, which can contain error message templates and placeholders.
  • checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs): Check whether the parameter is null, and throw a NullPointerException exception, which can contain error message templates and placeholders.
  • checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs): Check whether the object state is as expected, and throw an IllegalStateException, which can contain error message templates and placeholders.
  • checkElementIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs): Check whether the subscript is within the range of the collection, and throw an IndexOutOfBoundsException exception, which can contain error message templates and placeholders.
  • checkPositionIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs): Check whether the subscript is within the range of the collection, which can be equal to the size of the collection, and throw IndexOutOfBoundsException, which can contain error message templates and placeholders.
  • checkPositionIndexes(int start, int end, int size): Check whether the start subscript and end subscript are within the range of the collection, and throw an IndexOutOfBoundsException exception.
public class PreconditionsDemo {
    public static void main(String[] args) {
        // 检查参数是否符合预期,并抛出IllegalArgumentException异常,可以包含错误信息模板和占位符
        String str1 = "abc";
        Preconditions.checkArgument(str1.length() < 3, "字符串长度必须小于3");
        // 检查参数是否为null,并抛出NullPointerException异常,可以包含错误信息模板和占位符
        String str2 = null;
        Preconditions.checkNotNull(str2, "字符串不能为空");
        // 检查对象状态是否符合预期,并抛出IllegalStateException异常,可以包含错误信息模板和占位符
        boolean flag1 = false;
        Preconditions.checkState(flag1, "状态不正确");
        // 检查下标是否在集合的范围内,并抛出IndexOutOfBoundsException异常,可以包含错误信息模板和占位符
        List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5);
        Preconditions.checkElementIndex(6, list1.size(), "下标越界");
        // 检查下标是否在集合的范围内,可以等于集合的大小,并抛出IndexOutOfBoundsException异常,可以包含错误信息模板和占位符
        List<Integer> list2 = Lists.newArrayList(1, 2, 3, 4, 5);
        Preconditions.checkPositionIndex(5, list2.size(), "下标越界");
        // 检查开始下标和结束下标是否在集合的范围内,并抛出IndexOutOfBoundsException异常
        List<Integer> list3 = Lists.newArrayList(1, 2, 3, 4, 5);
        Preconditions.checkPositionIndexes(2, 6, list3.size());
        // 可以在错误信息中使用占位符
        int value1 = 101;
        Preconditions.checkArgument(value1 <= 100, "值必须小于等于 %s", 100);
        // 可以使用Supplier来避免计算开销
        int value2 = 101;
        Preconditions.checkArgument(value2 <= 100, () -> "值必须小于等于 " + 100);
}

cacheBuilder

Cache is a caching tool class provided by Guava, which can help us cache data in memory.

  1. Cache Loading: Specifies the cache loading mechanism. You can define how to load data that does not exist in the cache by passing a CacheLoader object. CacheLoader is an abstract class that needs to implement the load method to load the corresponding value according to the key.
  2. Cache size limit: Set the maximum capacity of the cache. When the cache exceeds the set capacity, some strategies (such as using LRU or FIFO) can be used to automatically eliminate some infrequently used cache items. The maximum size of the cache can be set using the maximumSize method.
  3. Expiration time: Set the expiration time for the cache item. The expiration time after writing or accessing the cache item can be set through the expireAfterWrite or expireAfterAccess method.
  4. Weak References to Keys or Values: CacheBuilder provides options to hold cached keys or values ​​using weak references. When a key or value is no longer referenced elsewhere, the cache automatically removes it from memory to avoid memory leaks.
  5. Statistical information: CacheBuilder provides some statistical information, including cache hit rate, loading times, loading success rate, etc. The collection of statistics can be turned on by calling the recordStats method.
@SneakyThrows
private static void testCache() {
    // 创建一个缓存实例
    Cache<String, String> cache = CacheBuilder.newBuilder()
        // 最大容量为100个缓存项
        .maximumSize(100)
        // 10分钟后过期
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build();

    // 向缓存中存入数据
    cache.put("key1", "value1");
    cache.put("key2", "value2");

    // 从缓存中获取数据
    String value1 = cache.getIfPresent("key1");
    // 输出: Value1: value1
    System.out.println("Value1: " + value1);

    // 存中存在,则返回对应的值;如果缓存中不存在,则使用提供的函数加载新的值,并将其添加到缓存中
    String value3 = cache.get("key3", () -> "value3");
    // 输出: Value3: value3
    System.out.println("Value3: " + value3);

    // 获取缓存的统计信息
    CacheStats stats = cache.stats();
    // 输出: Hit Rate: 1.0
    System.out.println("Hit Rate: " + stats.hitRate());
}

The above are the common usage scenarios. Partners are also welcome to share the methods of commonly used tool libraries.

Together shigen, every day is different!

Guess you like

Origin blog.csdn.net/weixin_55768452/article/details/132602218