1

How to get List<String> from List<Object[]> by converting the first element of array to String?

I tried writing like below but casting is not happening,

List<String> results = query.getResultList()
.stream()
.map(result ->{
 Object[]  temp =  (Object[]) result;
 return temp[0].toString();
})
.collect(Collectors.toList());

Below image shows type of results list enter image description here I am getting Error:java: incompatible types: java.lang.Object cannot be converted to java.util.List. How to do this correctly using Java 8?

12
  • 3
    Back up two steps here. First, what is the precise result of getResultList()? Second, what framework are you using to do these queries (JPA, Hibernate), and can you use a type-safe approach? Commented Jan 21, 2016 at 19:06
  • 2
    If you want a list why are you returning only the first element? Groovy? Commented Jan 21, 2016 at 19:06
  • 2
    What do you mean "casting is not happening"? What is happening? Commented Jan 21, 2016 at 19:06
  • Why do you query multiple fields if you just want one? What's the query? Commented Jan 21, 2016 at 19:10
  • 1
    Looks right to me. What's wrong? Commented Jan 21, 2016 at 19:11

1 Answer 1

16

query.getResultList() returns raw List. As mentioned by @Makoto in comment, try to use type-safe API. But if you intend to use the current API, add type casting (which will generate warning though).

List<String> results = ((List<Object[]>) query.getResultList())
.stream()
.map(result -> result[0].toString())
.collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

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.