chrisrhyno2003
chrisrhyno2003

Reputation: 4197

Using java stream and collect for a generic type

I am converting a list of strings to a list of a specific type. The list of strings can be converted to the other type with the help of gson since the strings are deserialized objects. I am using a lambda function to make the conversion.

My current code looks like:

List<String> myObject = myMethod.get(...);
Type typeObject= new TypeToken<T>(){}.getType();
List<T> myTransformedObject = myObject.stream()
                                .map(x-> gson.fromJson(x, typeObject))
                                .collect(Collectors.toList())); 

i get an error saying - "No instances of type variables exist so that Object confirms to T.

What am I missing?

Upvotes: 0

Views: 3966

Answers (2)

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

If you want to make your code generic, you should use a method with a bounded type parameter as next:

public <T> List<T> transform(Class<T> type) {
    return myObject.stream()
        .map(x-> gson.fromJson(x, type))
        .collect(Collectors.toList());
}

As you can see above, you have to provide the target class explicitly otherwise it cannot work.

Upvotes: 1

Sergii Getman
Sergii Getman

Reputation: 4381

Actually if you pass class object to gson.from(x, YourClass.class) it's works fine:

@Test
public void testStack() throws Exception {
    List<String> myObject = asList("{name: John}");
    Type typeObject= new TypeToken<Person>(){}.getType();
    List<Person> myTransformedObject = myObject.stream()
            .map(x-> gson.fromJson(x, Person.class))
            .collect(Collectors.toList());
    myObject.forEach(System.out::println);
}

class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

}

Upvotes: 0

Related Questions