我有一个如下所示的对象数组列表
List<Model> list= new ArrayList<Model>();
模型对象有两个属性,两者都是整数。
- ID
- 计数
现在我想将这个数组列表转换为 HashMap ,其中 id 是键,count 是值:
Map<Integer,Integer> convertedmap=new HashMap<Integer,Integer>();
有任何帮助吗?
最佳答案
迭代列表并在映射中为每个迭代的模型对象添加一个新元素:
Map<Integer,Integer> convertedmap = new HashMap<Integer,Integer>();
for (Model model : list){
convertedmap.put(model.getId(), model.getCount());
}
注意:如果 list
的 Model
实例的 id
字段具有相同的值,则列表中具有相同 id 的最后一个实例将覆盖创建的 map 中以前的实例。
你可以检查一下。
此外,您还可以使用 Java 8 的 Collectors.toMap()
方法来执行该作业:
Map<Integer, Integer> convertedmap = list.stream().collect(
Collectors.toMap(Model::getId, Model::getCount));
它比经典的循环迭代有优势。
如果 map 中用作键的 id
值在 list
中具有重复的值,则会引发 IllegalStateException : Duplicate key...
而不是默默地覆盖 map 。
关于java - 如何将对象数组列表转换为 HashMap ,其中键和值是对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343549/