SelfSurgery
SelfSurgery

Reputation: 382

Stream operation returns an Object instead of a List

I have the following code that executes as I intend:

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld{

 public static void main(String []args){
    HelloWorld.TreeNode rootNode = new HelloWorld().new TreeNode<Integer>(4);
    List<Integer> traversal = rootNode.inorderTraversal();
    // Prints 4
    System.out.println(
        String.join(",",
            traversal
                .stream()
                .map(Object::toString)
                .collect(Collectors.toList())
        )
    );
 }

 class TreeNode<K extends Comparable<K>> {

     TreeNode<K> left;
     TreeNode<K> right;
     K val;

     TreeNode(K val, TreeNode<K> left, TreeNode<K> right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }

     TreeNode(K val) {
         this(val, null, null);
     }

     List<K> inorderTraversal() {
         List<K> list = new ArrayList<>();
         list.add(this.val);
         return list;
     }

 }
}

However, if I replace the commented line with

System.out.println(
    String.join(",",
        rootNode.inorderTraversal()
            .stream()
            .map(Object::toString)
            .collect(Collectors.toList())
    )
);

I get the following error:

HelloWorld.java:14: error: no suitable method found for join(String,Object)
        String.join(",",
              ^
method String.join(CharSequence,CharSequence...) is not applicable
  (varargs mismatch; Object cannot be converted to CharSequence)
method String.join(CharSequence,Iterable<? extends CharSequence>) is not 
applicable
  (argument mismatch; Object cannot be converted to Iterable<? extends 
CharSequence>)
Note: HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

I saw this very similar issue (Why does this java 8 stream operation evaluate to Object instead of List<Object> or just List?), but I don't see how my solution doesn't circumvent the problem that user had because rootNode.inorderTraversal() return a List<Integer> instead of a List.

Thanks in advance for any assistance!

Upvotes: 4

Views: 288

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

This is because you are using raw types. Parameterize it with the generic types like so.

HelloWorld.TreeNode<Integer> rootNode = new HelloWorld().new TreeNode<>(4);

This will fix the issue. If you don't supply a generic type parameter on the left-hand side, the List is declared as a raw type.

Upvotes: 4

Related Questions