首页 > 其他 > 详细

日常编码小技巧

时间:2021-06-04 18:09:48      阅读:26      评论:0      收藏:0      [点我收藏+]

Java基础:

List转Map集合:

 1 class ConvertUtil {
 2     
 3     private ConvertUtil() {
 4     }
 5     /**
 6      * 将List转为Map
 7      *
 8      * @param list         原数据
 9      * @param keyExtractor Key的抽取规则
10      * @param <K>          Key
11      * @param <V>          Value
12      * @return
13      */
14     public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> keyExtractor) {
15         if (list == null || list.isEmpty()) {
16             return new HashMap<>();
17         }
18         Map<K, V> map = new HashMap<>(list.size());
19         for (V element : list) {
20             K key = keyExtractor.apply(element);
21             if (key == null) {
22                 continue;
23             }
24             map.put(key, element);
25         }
26         return map;
27     }

使用:

1 public static void main(String[] args) {
2     // 1.创建List集合
3     List<? extends Serializable> list = new ArrayList<>(Arrays.asList(1, 2, 42, "23"));
4     // 2.调用方法将list集合转map集合
5     Map<? extends Serializable, ? extends Serializable> map = listToMap(list, Function.identity());
6     // 3.遍历map集合
7     Set<? extends Map.Entry<? extends Serializable, ? extends Serializable>> entries = map.entrySet();
8     entries.forEach(System.out::println);
9 }

输出:

技术分享图片

 

日常编码小技巧

原文:https://www.cnblogs.com/zhangzhixi/p/14849998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!