How do I fix a mismatching type error when returning the result of a stream collector?

Viewed 102

I have this piece of code:

public static List <java.util.Date> map(List <Object[]> queryRows) {

  List <Object> list = Arrays.asList(queryRows);
  List <Object> list2 = Arrays.asList(list.get(0));

  return ((List) list2.get(0))
        .stream()
        .map(x -> new java.util.Date(((java.sql.Timestamp) x).getTime()))
        .collect(Collectors.toList());
}

but I have this compilation error:

Required type:List<java.util.Date>
Provided:Object
4 Answers

If you know the elements are of type Timestamp, you should avoid using the raw type(the reason why the type of Stream is not inferred and everything ends up being inferred as Object) and work with

return ((List<java.sql.Timestamp>) list2.get(0))
            .stream()
            .map(x -> new Date(x.getTime()))
            .collect(Collectors.toList());

You can try this.

List <Object> list = Arrays.asList(queryRows);
List <Object> list2 = Arrays.asList(list.get(0));

return  Arrays.asList(list2.get(0))
          .stream()
          .map(x -> new java.util.Date(((java.sql.Timestamp) x).getTime()))
          .collect(Collectors.toList());

This should work.

Cast the return type in the lambda expression to List<Date>:

return ((List<Date>) list2.get(0))
                .stream()
                .map(x-> new Date((x).getTime()))
                .collect(Collectors.toList());

You need to add an import statement or change Date to java.util.Date. Another issue is you should not have white space between - >. It should be ->

Related