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 + '\'' +
'}';
}
}
}
- 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
- 59
- 60
- 61
- 62
使用guava
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
@Override
public Long apply(User user) {
return user.getId();
}
});
- 1
- 2
- 3
- 4
- 5
- 6
使用JDK1.8
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
- 1
看来还是使用JDK 1.8方便一些。另外,转换成map
的时候,可能出现key
一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map
的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
- 1
- 2
有时候,希望得到的map
的值不是对象,而是对象的某个属性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
- 1
- 2
</div><div><div></div></div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-60ecaf1f42.css" rel="stylesheet">
</div>