1、for循環
。。。
2、使用guava
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() { @Override public Long apply(User user) { return user.getId(); } });
3、使用JDK1.8
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
看來還是使用JDK 1.8方便一些。另外,轉換成map
的時候,可能出現key
一樣的情況,如果不指定一個覆蓋規則,上面的代碼是會報錯的。轉成map
的時候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
有時候,希望得到的map
的值不是對象,而是對象的某個屬性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));