1

I recently started working in Java streams. I was trying to get the String values out of the result set of one of my SQL queries. The result set selects just a String/Varchar column from the DB.

So I did:

List<String> list = query.getResultList().stream().map(Object::toString).collect(Collectors.toList());

or:

List<String> list =  = query.getResultList().stream().map(String::valueOf).collect(Collectors.toList());

I believe the map takes a function to convert data from one type to another. In this case, from Object to String and then collect them in a String list.

But the above code shows compile time error: Cannot convert from Object to List of string.

Please suggest me the correct way of doing this and explain what is wrong with my understanding.

2 Answers 2

4

Because Query.getResultList() returns a raw type List it will break stream pipeline which is heavily based on generic type information. Raw type are effectively removing all information about generic types when used so stream collector returns Object.

You can work around it by manually introducing the generic type with a cast to List<?>:

List<String> collect = ((List<?>) query.getResultList()).stream()
    .map(Object::toString)
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

3

Use a TypedQuery<String> instead of a Query.

This does away with the rather superfluous remapping, and introduces type-safeness.

Comments

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.