Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
Ravi Avatar asked May 31 '26 16:05

Ravi


1 Answers

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());
like image 118
Lukas Körfer Avatar answered Jun 04 '26 01:06

Lukas Körfer