Return stream from user data class

I am working on a program that creates its own generic LinkedList class, and I would like to be able to generate a stream from it by calling stream () on the object. I looked through the documents and did not find anything that could help me do this as an interface for implementation (similarly ... iterable, comparator, comparable). I was thinking of creating a stream method that returns a stream with Arrays.stream, from an array created by iterating over the linked list and the destination of the elements. This is good, also this general class, I would like its parameters to be limited to two classes that have no inheritance relationship. Type type <Person or alien> can be reached

+4
source share
1 answer

I assume that your own LinkedList class has an iterator () method. I also assume that it has a constant size () method. Having made these assumptions, you can implement the stream () method using the following code:

public Stream<T> stream() {
    Iterator<T> it = iterator();
    int characteristics = 0;  // see characteristics docs in [Spliterator][1]
    Spliterator<T> spliterator = Spliterators.spliterator(it, size(), charactistics);  // see [Spliterators][2]
    return StreamSupport.stream(spliterator, false);  // see [StreamSupport][3]
}
0
source

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


All Articles