一个需求是这样:根据list,转为map。
假设List
java8以前得这样写:
1 2 3 4 |
Map<String, User> map = new HashMap<String, User>(); for (User user : list) { map.put(user.getId(), User); } |
java8利用lambda和stream这样即可,还是挺方便的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Map<String, User> map = Util.listToMapWithKey(list, User::getId); /** * 遍历list, 并返回map, 其中key由keyMapper指定 * @author bianbian.org * @param list * @param keyMapper * @param <K> * @param <V> * @return */ public static <K, V> Map<K, V> listToMapWithKey(List<V> list, Function<? super V, ? extends K> keyMapper) { if (list == null) return null; return list.stream() .collect(Collectors.toMap( keyMapper, v -> v )); } |
看起来复杂,好处是支持泛型。如
1 |
Map<Integer, Bianbian> map = Util.listToMapWithKey(list, Bianbian::getSmell); |