Java源码中你不知道但经常写的超便捷工具类

日常中我们会写很多工具类,但其实源码中已经有了,但可能你没有发现,那么总结一下源码中已经封装好可以直接使用的方法或者工具类。

1. HashMap - computeIfAbsent()

这个方法从名字可以知道【运算如果不存在】,作用就是如果key在map中不存在就会运算后面的Function函数返回值的value后,插入map。然后方法返回value。

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

源码SpringBoot中使用:

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

对比:
HashMap - putIfAbsent()
最大区别在于如果map中不存在这个key,会在插入kv后,返回null。而computeIfAbsent返回插入的v。

2.StringUtils-commaDelimitedListToStringArray

方法名称就对字符串进行逗号",“分割后转化为array,我们之前最常用的就是split(”,")。

String[] commaDelimitedListToStringArray(@Nullable String str)

SpringBoot中使用

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

3.HashMap-replaceAll

对map中所有值进行替换成新值,k,v处理后将所有v替换成Function返回值。

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

SpringBoot中使用

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

4.Collectors.collectingAndThen

对流进行收集,收集后执行一个Function函数,以收集后的集合为参数,返回任何类型

第一个参数是以什么方法收集,通常是Collectors.toList 收集为列表

第二个参数是收集后要操作的什么Function函数

扫描二维码关注公众号,回复: 16972909 查看本文章

SpringBoot中使用:

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

总结

在学习源码时候会经常看到大神用这些方法,总结一下一是方便自己学习,明白使用目的,二是之后工作中加以使用,不比重复造轮子。

猜你喜欢

转载自blog.csdn.net/qq_40922616/article/details/121406446