Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect to a List using streams returning my own List implementation? [duplicate]

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());
}
like image 563
Garrett Smith Avatar asked Oct 23 '15 10:10

Garrett Smith


People also ask

How do you find duplicate elements in an array using Stream?

Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.


1 Answers

Assuming the MyList type is a Collection, you can use Collectors.toCollection:

MyList<String> list2 = aList.stream().collect(toCollection(MyList::new));
like image 84
Tunaki Avatar answered Sep 20 '22 14:09

Tunaki