1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| @Accessors(chain = true) @lombok.Data class User { private String id; private String name; }
List<User> userList = Lists.newArrayList( new User().setId("A").setName("张三"), new User().setId("B").setName("李四"), new User().setId("C").setName("王五") );
Map<String, String> map = new HashMap<>(); for (User user : userList) { map.put(user.getId(), user.getName()); }
Map<String, String> map = new HashMap<>(); for (User user : userList) { map.put(user.getId(), user.getName()); }
userList.stream().collect(Collectors.toMap(User::getId, User::getName));
userList.stream().collect(Collectors.toMap(User::getId, t -> t));
userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper); toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction); toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier);
userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1 + n2)); userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1));
userList.stream().collect( Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1, TreeMap::new) );
|