How to compile into a list using streams returning my own implementation of List?

How to assemble a stream into a list that I define by subtype?

In other words, I would like this test to pass. What should I do in the commented line to convert the stream to an instance 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());
}
+4
source share
1 answer

Assuming the type MyListis Collection, you can use Collectors.toCollection:

MyList<String> list2 = aList.stream().collect(toCollection(MyList::new));
+5
source

Source: https://habr.com/ru/post/1612907/


All Articles