list集合转map 封装

// list 转map 很多情况下,需要遍历2层for循环 ,时间复杂度为O(n的平方),可以借助 转map,遍历循环一层for循环,需要的从map中取数据,提升速度,
//map的时间复杂度为O(1)可忽略不计 ,一下是对list转map的封装
public
static <T, K> Map<K, T> list2Map(List<T> list, Function<? super T, ? extends K> keyMapper) { if (list == null || list.size() == 0) { return new HashMap<>(); } return list.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (key1, key2) -> key2)); }       
//使用案例
   Map<Long, User> map = list2Map(list, User::getId);
 

 

posted @ 2024-03-05 14:37  沐海风  阅读(16)  评论(0编辑  收藏  举报