<>for loop
import com.google.common.base.Function; import com.google.common.collect.Maps;
import java.util.ArrayList; import java.util.HashMap; import java.util.List;
import java.util.Map; public class ListToMap { public static void main(String[]
args) { List<User> userList = new ArrayList<>(); User user1 = new User();
user1.setId(1L); user1.setAge("12"); User user2 = new User(); user2.setId(2L);
user2.setAge("13"); userList.add(user1); userList.add(user2); Map<Long, User>
maps = new HashMap<>(); for (User user : userList) { maps.put(user.getId(),
user); } System.out.println(maps); } public static class User { private Long
id; private String age; public Long getId() { return id; } public void
setId(Long id) { this.id = id; } public String getAge() { return age; } public
void setAge(String age) { this.age = age; } @Override public String toString()
{ return "User{" + "id=" + id + ", age='" + age + '\'' + '}'; } } }
<> use guava
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
@Override public Long apply(User user) { return user.getId(); } });
<> use JDK1.8
Map<Long, User> maps =
userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
It seems to be still used JDK 1.8 It's more convenient . in addition , convert to map When , May appear key The same situation , If you do not specify an override rule , The code above will report an error . Into map
When , It is best to use the following method :
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,
Function.identity(), (key1, key2) -> key2));
occasionally , Hope to get map The value of is not an object , It's an attribute of the object , Then you can use the following method :
Map<Long, String> maps =
userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1,
key2) -> key2));

Technology
©2019-2020 Toolsou All rights reserved,
( Super detail )Eclipse Using tutorials —— use Eclipse Create first HelloWorld! Database operation 5 code implementation mysql Addition, deletion, modification and query of database What can MCU do , Do you have any interesting works made by MCU or open source hardware Go to the interview after reading this , Steady over ~~ Single linked list of primary data structure (C Language implementation )SQL Comprehensive questions Employee unit comprehensive questions Python Implementation of Hanoi Tower code VHDL——JK trigger It's over , Starting salary 30k