Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HashMap to ArrayList

I just want to move the transitionHash map values into the cardholderDataRecords arraylist.

HashMap<String,ExceptionLifeCycleDataBean> transitionHash = new HashMap<String,ExceptionLifeCycleDataBean>();  ArrayList<ExceptionLifeCycleDataBean> cardholderDataRecords = new ArrayList<ExceptionLifeCycleDataBean>(); 

i am doing as

cardholderDataRecords.add((ExceptionLifeCycleDataBean) transitionHash.values()); 

It's throwing

java.lang.ClassCastException: java.util.HashMap$Values cannot be cast to com.reportss.bean.ExceptionLifeCycleDataBean 
like image 997
Mdhar9e Avatar asked May 28 '12 06:05

Mdhar9e


People also ask

Can we convert HashMap to array?

One way to convert is to use the constructor of the ArrayList. In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap.

Can you have an ArrayList of HashMap?

Conversion of HashMap to ArrayList A HashMap contains key-value pairs, there are three ways to convert a HashMap to an ArrayList: Converting the HashMap keys into an ArrayList. Converting the HashMap values into an ArrayList. Converting the HashMap key-value pairs into an ArrayList.

Is it possible to convert keys in the map to array or ArrayList?

You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.

Is HashMap better than ArrayList?

ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively.


1 Answers

You're trying to cast the collection of values to a single ExceptionLifeCycleDataBean.

You can very easily get the list though:

List<ExceptionLifeCycleDataBean> beans =     new ArrayList<ExceptionLifeCycleDataBean>(transitionHash.values()); 

Or to add to an existing collection, with:

cardholderDataRecords.addAll(transitionHash.values()); 

No casts necessary.

like image 83
Jon Skeet Avatar answered Oct 04 '22 13:10

Jon Skeet