- I have
map<Integer,Object>
- I want to put values of the map to te
List<String>
- The
ArrayList<String>(map.values)
gives me a error
The constructor ArrayList<String>(Collection<Object>) is undefined
EDIT: Thank you. But I did not make myself clear. My object are class objects name TravelData which have few variables like doubles, dates and strings. I processing them and put into map like <Integer,TravelData>.
Then i must to put them to List<String>
and print them all. I cant change type of list :(
solved by: Override toString method
multiLangOffers = new ArrayList<String>();
for (TravelData value : offers.values()) {
multiLangOffers.add(value.toString());
}
Thank you all !
Best How To :
Depending on that you initialized your Map with <Integer, Object>
a call to Map.values()
will return Collection<Object>
. This means you had to initialize your ArrayList
as:
List<Object> value = ArrayList<Object>(map.values());
But this would be useless, because the return of map.values()
is already a collection and when you are not depending on API parts of Interface List
you could stick to that.
But you want a List<String>
with the values of the Map which are String then you have to do something like this:
List<String> stringValues = new ArrayList<String>();
for (Object value : map.values()) {
if (value instanceof String) {
stringValues.add((String) value);
}
}
This is iterating over all Values as Objects and then checks the instance type of value on String. if so, add the value as String to your List.
So makes the questions strange, but depending on comment. If the map is handling custom complex Object instead of Object
. Then you have to access the desired String value of that Object manualy:
List<String> stringValues = new ArrayList<String>();
for (ComplexObj value : map.values()) {
stringValues.add(value.getDesiredStringValueGetterMethodIfYouUseBeanSyntax());
}