简体   繁体   中英

How to convert a object arraylist into a hashmap where key and value are the objects attributes

I have a object arraylist like below

List<Model> list= new ArrayList<Model>();

The Model object has two attributes where both are integers.

  1. id
  2. count

Now I want to convert this arraylist into a Hash Map where id is the key and count is the value:

Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

Any help is appreciated?

Iterate on the list and add a new element in the map for each iterated Model object :

Map<Integer,Integer> convertedmap = new  HashMap<Integer,Integer>();
for (Model model : list){
   convertedmap.put(model.getId(), model.getCount());
}

Beware : If list has Model instances with as id field the same value, the last instance in the List with the same id will overwrite the previous instance(s) in the created map.

You could do a check about it.

Otherwise, you can also perform the job by using the Collectors.toMap() method of Java 8 :

Map<Integer, Integer> convertedmap = list.stream().collect(
                Collectors.toMap(Model::getId, Model::getCount));

It has an advantage over the classic loop iteration.
If the id value that is used as key in the map has duplicated values in the list , it will rise IllegalStateException : Duplicate key... rather than overwriting silently the map.

You can do this with for loop.

List<Model> list= new ArrayList<Model>();
Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

for(int i=0;i<list.size();i++){
Model model = list.get(i);

convertedmap.put(model.getId(),model.getCount());
}

First of all complete your POJO class Model with proper setters/getters then you can iterate the whole ArrayList list and put the values in Map convertedmap like :

Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

for (Model md : list) {
   convertedmap.put(md.getId(), md.getCount());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM