Java ArrayList 到 HashMap 的映射
我有页面被给予 ArrayList
我不知道独特类型或文档的数量。
我想将此 ArrayList 排序为 HashMap
一些伪代码希望
for (int i = 0; i < documents.size(); i++)
{
if there is an array for documents[i].type
add to this array
else create a new array for this type
add document[i].type and the array of documents with matching type to the hashmap
}
我知道这是错误的方法并且显然行不通。我愿意接受任何建议。
谢谢
I have page gets given an ArrayList<Document> where each document has a property called type.
I don't know the number of unique types or documents.
I want to sort this ArrayList into a HashMap<type, document[]> but am having some trouble getting my head around it.
Some pseudo-code would like like
for (int i = 0; i < documents.size(); i++)
{
if there is an array for documents[i].type
add to this array
else create a new array for this type
add document[i].type and the array of documents with matching type to the hashmap
}
I know this is the wrong approach and clearly won't work. I am open to any suggestions.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您要查找的术语不是按类型排序,而是按类型索引。 Guava 的 Multimap 接口旨在将键映射到多个值,而无需处理集合的所有麻烦价值观。特别是,Guava 有一个方法,旨在完全执行您想要执行的操作:
这与执行: 几乎相同,
只是生成的多重映射是不可变的。另请注意,上面的内容几乎与马克的示例完全相同。
I think rather than sorting by type, the term you're looking for is indexing by type. Guava's Multimap interface is designed for mapping keys to multiple values without all the hassle of dealing with the collections of values. In particular, Guava has a method that's designed to do exactly what you're trying to do:
This is pretty much the same as doing:
except that the resulting multimap is immutable. Note also that the above is almost exactly equivalent to Mark's example.