Question

I'm trying to use a third party library that has a method signature like so:

testMethod(Iterable<HashMap<String,Date>>, String, String)

How can I pass an iterable to this method?

I wanted to do something like the following, but it fails:

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

testMethod(items, "more", "data");
Was it helpful?

Solution

You need to pass an Iterable or one of its subtypes, e.g., List, Set, etc. So, you can add the HashMap to a List, and pass it:

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

List<HashMap<String, Date>> list = new ArrayList<HashMap<String, Date>>();
list.add(items);

testMethod(list, "more", "data");

Note that since the parameter type is Iterable<HashMap<String, Date>>, you can only pass - List<HashMap...> or Set<HashMap...>, etc. You cannot pass a List<Map..> in it.

OTHER TIPS

You need to wrap your Map with some object which is Iterable. Using Arrays.asList(T... a) ought to work here.

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

testMethod(Arrays.asList(list), "more", "data");`

You need to pass an Iterable to the method. It looks like HashMap does not implement the Iterable interface. You could either subclass Map and add the Iterable interface to your subclass, or pass in a list of your map's entries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top