Question

Use collect to return List<particular type> instead of List<Object>

I want to collect List<TestClone>, but looks like .collect() returns only List<Object>. Is there a way I can get List<TestClone>?

I know .toArray() is there, but want an ArrayList.

public static List<TestClone> getTypes(List<TestClone> args)
{
    return args.stream().map(e -> {
        if (e.schema == null)
        {
            return getAllExportArgs(e);
        }
        else
        {
            return e;
        }
    }).collect(Collectors.toCollection(ArrayList<TestClone>::new)); //TODO: ?
}

public static List<TestClone> getAllExportArgs(TestClone args)
{
    //returns List<TestClone>
}
 4  90  4
1 Jan 1970

Solution

 8

The issue is with the lambda you call in map - the if branch returns a List<TestClone>, while the else branch returns a TestClone. The intersection between these two types is probably an Object.

Assuming that this is not intentional, one approach is to produce streams in both branches and then flatten them, so you end up with one continuous Steam<TestClone>, that can then be easily collected to a list:

public static List<TestClone> getTypes(List<TestClone> args)
{
    return args.stream().flatMap(e -> {
        if (e.schema == null)
        {
            return getAllExportArgs(e).stream();
        }
        else
        {
            return Stream.of(e);
        }
    }).collect(Collectors.toCollection(ArrayList<TestClone>::new)); 
}
2024-07-15
Mureinik