如何将流收集到我指定的子类型列表中?
换句话说,我希望这个测试通过。如何在注释行上将流转换为MyList
实例?
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());
}
答案 0 :(得分:5)
假设Collection
类型为MyList<String> list2 = aList.stream().collect(toCollection(MyList::new));
,您可以使用Collectors.toCollection
:
[Enum].TryParse