1.for循环
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
|
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 + '\ '' + '}' ; } } } |
2.使用guava
1
2
3
4
5
6
|
map< long , user> maps = maps.uniqueindex(userlist, new function<user, long >() { @override public long apply(user user) { return user.getid(); } }); |
3.使用jdk1.8
1
|
map< long , user> maps = userlist.stream().collect(collectors.tomap(user::getid, user -> user)); |
看来还是使用jdk 1.8方便一些。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/linsongbin1/article/details/79801952