Saurabh Tiwari
Saurabh Tiwari

Reputation: 5131

Converting from List of Object to List of String using streams

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.

Upvotes: 1

Views: 9821

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

Use a TypedQuery<String> instead of a Query.

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

Upvotes: 3

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

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());

Upvotes: 4

Related Questions