Skip to content

Mixins : Streamable

johnmcclean-aol edited this page Feb 24, 2016 · 3 revisions

Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react

All new develpoment on cyclops occurs in cyclops-react. Older modules are still available in maven central.

screen shot 2016-02-22 at 8 44 42 pm

Streamable

com.aol.cyclops.lambda.api.Streamable represents a datastructure that can generate a Stream. Replayable Streamables can be lazily constructed from traverse-once Java 8 Streams, or Collections and more.

Objects can be coerced to Streamable, if they don't implement it already, via

  • AsStreamable.asStreamable
  • As.asStreamable

When stream() is called on coerced Streamables

  • If the coerced Object is itself a Stream, a new copy will be returned each time.
  • If the Object is an iterable a new Stream will be generated from that
  • Otherwise, if the object has a stream() or toStream() method it will be called using JDK InvokeDynamic functionality
  • If the Object does not have a stream() or toStream() method, it will be coereced to Decomposable which provides a mechanism to create an Iterable for the Object (from it's fields). The Stream will be generated via the Iterable unapply() method.

Example : coercing a Stream to Streamable

A Stream can be coerced to a Stremable, and stream() invoked multiple times over the same Streamable instance -

       Stream<Integer> stream = Stream.of(1,2,3,4,5);
       Streamable<Integer> streamable = As.<Integer>asStreamable(stream);
       List<Integer> result1 = streamable.stream().map(i->i+2).collect(Collectors.toList());
       List<Integer> result2 = streamable.stream().map(i->i+2).collect(Collectors.toList());
       List<Integer> result3 = streamable.stream().map(i->i+2).collect(Collectors.toList());
		
	assertThat(result1,equalTo(Arrays.asList(3,4,5,6,7)));
	assertThat(result1,equalTo(result2));
	assertThat(result1,equalTo(result3));

Example : coercing a List to Streamable

     List<Integer> result = As.<Integer>asStreamable(Arrays.asList(1,2,3)).stream().map(i->i+2).collect(Collectors.toList());
		
    assertThat(result,equalTo(Arrays.asList(3,4,5)));
Clone this wiki locally