且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中将对象列表转换为散列表

更新时间:2022-12-14 20:15:33

Create a Map of the type you like (HashMap, TreeMap, HashTable,...) and then iterate through your list and add all elements one by one.

There is no better way (except if you are willing to code your own map that is backed by this list which - in some cases - would be really good).

You MAY set some options on your Map type before adding the elements (such as setting the size) because you already know how many elements to add. That may increase performance a little. Depends heavily on your use case.

EDIT: I said this because I understand your question in a way that your lists contains POJOs with a string and an integer attribute. If that's different, then the answer may be different.