Ravi
Ravi

Reputation: 101

convert TreeMap<String,Object> to List<HashMap<String,Object>>

I have a TreeMap<String,Object> which contains Objects that are actually HashMap<String,Object>. I want to convert this to List<HashMap<String,Object>>. I was trying to convert it using Java 8 and wrote the following code which is giving compilation error due to conversion from List<Object> to List<HashMap<String,Object>>.

public static void main(String[] args) {
        TreeMap<String,Object> treeMap = new TreeMap<String,Object>();
        HashMap<String,Object> map1 = new HashMap<String,Object>();
        map1.put("a",1);
        map1.put("b","2");
        map1.put("c",5);
        treeMap.put("01",map1);
        HashMap<String,Object> map2 = new HashMap<String,Object>();
        map2.put("a",5);
        map2.put("b","7");
        map2.put("c",6);
        treeMap.put("02",map2);

//this conversion is not working as Java is not allowing to convert from List<Object> to List<HashMap<String,Object>>
        List<HashMap<String,Object>> list= treeMap.values().stream()
                .collect(Collectors.toList());
    }

Changing the TreeMap to TreeMap<String,HashMap<String,Object>> works but I don't want to make this change as I am passing this to a separate method which expects TreeMap<String,Object>.

Please suggest.

Upvotes: 3

Views: 2355

Answers (2)

Malte Hartwig
Malte Hartwig

Reputation: 4555

I would start by giving treeMap the proper types: TreeMap<String, HashMap<String, Object>>.

You can then wrap the map and pass new TreeMap<String, Object>(treeMap) to that other method.

Nicer, as it does not require a new map, would be to follow Sean's comment and change that method's parameter from TreeMap<String, Object> to TreeMap<String, ?>, if you are allowed to do that.

Upvotes: 1

Lukas K&#246;rfer
Lukas K&#246;rfer

Reputation: 14523

Well, you define the treeMap to have Object values, this is why values().stream() returns a Stream<Object>. Either change your contract or you'll need to cast the elements in the stream:

List<HashMap<String,Object>> list= treeMap.values().stream()
    .map(element -> (HashMap<String,Object>)element)
    .collect(Collectors.toList());

Upvotes: 3

Related Questions