M
M
Maxim Kartavin2020-05-31 15:17:31
Java
Maxim Kartavin, 2020-05-31 15:17:31

How to get several from 2 objects via stream api?

there are two objects (obj1, obj2) of class A, each of them is a singly-directed list
i.e. contains a reference to the next object of class A, the last object refers to null

class A {
    private A next;      //ссылка на след объект

    public A getNext() {       //получить следующий объект
        return this.next;
    }
}


how can you use the stream API to put all objects into one stream (well, or add them to a collection)
without streams, this is easy to do, but I want to do it with the help of a stream

in my head something like
Stream.of( obj1, obj2 ). [ действие ] .collect(Collectors.toList())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-05-31
@short_infinity

Stream.of(obj1, obj2)
  .flatMap(o -> Stream.generate(o::getNext)
    .takeWhile(Objects::nonNull))
  .collect(Collectors.toList())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question