Reputation: 817
map<Integer,Object>
List<String>
ArrayList<String>(map.values)
gives me a errorThe 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 !
Upvotes: 2
Views: 6543
Reputation: 2690
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());
}
Upvotes: 3
Reputation: 1859
Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList
but here you are doing reverse as object can not be passed in string as it doesn't extends string
you can do two thing
you can make list of objects and all will work find
public class Test {
static List<Object> list = new ArrayList<Object>();
static Map<String, Object> map = new HashMap<String, Object>();
public static void main(String args[]) {
map.put("1", "test");
list = new ArrayList<Object>(map.values());
System.out.println(list.toString());
}
}
you can make map with value of type string
public class Test {
static List<String> list = new ArrayList<String>();
static Map<String, String> map = new HashMap<String, String>();
public static void main(String args[]) {
map.put("1", "test");
list = new ArrayList<String>(map.values());
System.out.println(list.toString());
}
}
Upvotes: 3
Reputation: 488
try that List list = new ArrayList(map.values());
Regards
Upvotes: 0