5

How to collect a stream into a list that is a subtype that I specify?

In other words, I'd like this test to pass. What should I do on the commented line to convert a stream to a MyList instance?

import org.junit.*;
import java.util.*;
import static java.util.stream.Collectors.*;
import static junit.framework.Assert.*;

@Test
public void collectUsingDifferentListType() {
    List<String> aList = new ArrayList<>();
    aList.add("A");
    aList.add("B");
    List<String> list1 = aList.stream().collect(toList());
    MyList<String> list2 = aList.stream().collect(toList(MyList::new));  // this doesn't exist, but I wish it did

    assertEquals(aList, list1);
    assertEquals(ArrayList.class, list1.getClass());
    assertEquals(aList, list2);
    assertEquals(MyList.class, list1.getClass());
}
4

1 回答 1

9

假设MyList类型是 a Collection,您可以使用Collectors.toCollection

MyList<String> list2 = aList.stream().collect(toCollection(MyList::new));
于 2015-10-23T10:49:40.133 回答