Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to create a stream from a Java object?

Tags:

With Collection everything is clear, but what about the following:

There is an object with a count() method and a getPart(int i) method. So extracting all objects leads to the following boilerplate code:

List<Part> result = new ArrayList<Part>(); for (int i = 0, i < object.count(), i++) {     result.add(object.getPart(i));         } return result.stream();  

Is there any standard way to pass just 2 producers: () -> object.count() and (int i) -> object.getPart(i) to create a stream? Like this:

SomeUtil.stream(object::count, object::getPart); 
like image 462
Cherry Avatar asked Feb 28 '17 08:02

Cherry


People also ask

How do you stream an object in Java?

Just use Stream. of() to create a stream from a bunch of object references. Besides regular object streams Java 8 ships with special kinds of streams for working with the primitive data types int , long and double . As you might have guessed it's IntStream , LongStream and DoubleStream .

Which of the following methods are used to create streams in Java?

Create a stream from Collection The Java Collection framework provides two methods, stream() and parallelStream() , to create a sequential and parallel stream from any collection, respectively.

Which class helps in creating a stream from a topic?

The Kafka Streams application consists of a single Java Class that creates a stream from the Kafka Topic.


1 Answers

Try this:

IntStream.range(0, object.count()).mapToObj(object::getPart); 
like image 148
MBec Avatar answered Sep 21 '22 13:09

MBec