Super convenient tool classes you don’t know but often write in Java source code

In our daily life, we write many tool classes, but they are already in the source code, but you may not have noticed them. Let’s summarize the methods or tool classes that have been encapsulated in the source code and can be used directly.

1. HashMap - computeIfAbsent()

This method can be known from the name [Operation if does not exist]. Its function is that if the key does not exist in the map, it will calculate the value returned by the subsequent Function function and insert it into the map. Then the method returns value.

public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Used in source code SpringBoot:

((List)result.computeIfAbsent(factoryTypeName, (key) -> {
    
    
    return new ArrayList();
})).add(factoryImplementationName.trim());

Comparison: The biggest difference between
HashMap - putIfAbsent()
is that if the key does not exist in the map, null will be returned after kv is inserted. And computeIfAbsent returns the inserted v.

2.StringUtils-commaDelimitedListToStringArray

The method name is to split the string with commas "," and convert it into an array. The most commonly used one before us is split(",").

String[] commaDelimitedListToStringArray(@Nullable String str)

Used in SpringBoot

String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());

3.HashMap-replaceAll

Replace all values ​​in the map with new values. After k and v are processed, replace all v with Function return values.

replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

Used in SpringBoot

result.replaceAll((factoryType, implementations) -> {
    
    
    return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
});

4.Collectors.collectingAndThen

Collect the stream, execute a Function function after collection, take the collected collection as a parameter, and return any type

The first parameter is the method to collect, usually Collectors.toList to collect as a list

The second parameter is the Function function to be operated after collection.

Used in SpringBoot:

return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

Summarize

When learning source code, you will often see masters using these methods. To sum up, firstly, it is convenient for you to learn and understand the purpose of use. Secondly, you can use them in your future work, which is not like reinventing the wheel.

おすすめ

転載: blog.csdn.net/qq_40922616/article/details/121406446