1

A list object containing a Map<String, String> objects need to pass as argument having parameter of type List<Map<String, Object>>. I need to cast it like this -

List<Map<String, Object>> objectList = (List<Map<String, Object>>) (Object) strList;

Is there any better approach here? Is it good idea to cast like given above? Will Java 8 Stream be a better option for conversion?

4
  • 1
    Hi and welcome. Could you show more of the context? Why is it passed as an Object? Why are you casting it to an Object in the first place? etc. Commented May 22, 2018 at 4:55
  • Can you change the API to accept a List<Map<String, ?>>? Commented May 22, 2018 at 4:57
  • I am getting the above list object strList from the web layer, my service layer api accept only of type objectList . so that is why need to cast and create objectList before passing it to service api. Commented May 22, 2018 at 4:59
  • 1
    @DavidConrad You might need List<? extends Map<String, ?>> Commented May 22, 2018 at 5:00

2 Answers 2

1

If you can, you can change the target parameter to type List<? extends Map<String, ?>>

If you want to construct a new object matching the target type,

List<Map<String, Object>> objectList = strList.stream()
        .map(map -> map.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> (Object)e.getValue())))
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

0

The following has an unsafe type cast warning, but I believe in the case suppressing warnings is justified as the data is known to be compatible.

List<Map<String, Object>> objectList = 
        list.stream()
            .map(m -> (Map<String, ?>) m)
            .map(m -> (Map<String, Object>) m) //warning
            .collect(Collectors.toList());

Although the stream has little more than just type casts, it still creates a new collection, so it would be better to just change your downstream API to accept both type arguments:

private static <T extends Object> void 
        doSomething(List<Map<String, T>> objectList) {}

And you can call it with either type:

List<Map<String, String>> list = null;
List<Map<String, Object>> objectList = null;

doSomething(objectList);
doSomething(list);

1 Comment

@Prem Joshi comments are appreciated. Does this answer your question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.