标签:ali zab param mamicode == 编码 color bsp loading
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 }
输出:
标签:ali zab param mamicode == 编码 color bsp loading
原文地址:https://www.cnblogs.com/zhangzhixi/p/14849998.html