如何使用返回我自己的List实现的流收集到List?

时间:2015-10-23 10:46:49

标签: java java-8 java-stream collectors

如何将流收集到我指定的子类型列表中?

换句话说,我希望这个测试通过。如何在注释行上将流转换为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());
}

1 个答案:

答案 0 :(得分:5)

假设Collection类型为MyList<String> list2 = aList.stream().collect(toCollection(MyList::new)); ,您可以使用Collectors.toCollection

[Enum].TryParse