Search code examples
javajava-streamclasscastexception

Convert List<Object[]> to list<String> Cast exception


I have a list with an array of objects (strings) :

 List<Object[]> params  = ...

I want to cast this list to a list of strings List

  List<Object> results = params.stream()
                            .flatMap(arr -> Arrays.stream(arr))
                            .collect(Collectors.toList());

Then I want to do something like that :

results.forEach(System.out::println);

I get this exception :

java.lang.ClassCastException: class java.lang.String cannot be cast to class [Ljava.lang.Object; (java.lang.String and [Ljava.lang.Object; are in module java.base of loader 'bootstrap')

This how I create the params :

 Query query = entityManager.createNativeQuery(sql);
 List<Object[]> params = query.getResultList();;

Solution

    • Stream the arrays
    • flatten the arrays into a stream of objects.
    • filter out non strings.
    • cast via a map remaining objects to strings
    • collect into a List
    List<Object> params = List.of(1, 2,
                       "hello",
                       "computer",  new Object(), 4.32,
                       new Object[]{1,2});
    
    List<String> strings = params.stream()
            .filter(ob -> ob instanceof String)
            .map(ob -> (String) ob)
            .collect(Collectors.toList(), "java");
    
    System.out.println(strings);
    

    Prints

    [hello, computer, java]