GlenKPeterson / Paguro

Generic, Null-safe, Immutable Collections and Functional Transformations for the JVM
Other
312 stars 24 forks source link

How to use Paguro with Java stream? #43

Closed viebel closed 3 years ago

viebel commented 3 years ago

Is there a simpler way to collect a stream into a Paguro data structure, than to collect in a Java collection and to convert to Paguro?

For the moment, here is how I do it:

var vec1 = PersistentVector.ofIter(List.of(10, 2, 3));
var vec2 = PersistentVector.ofIter(vec1.stream().sorted().map(x -> x + 1).collect(Collectors.toList()));
GlenKPeterson commented 3 years ago

The following code compiles with Java 11 and passes a test with Junit. It does not, however, use Java streams:

var vec1 = vec(10, 2, 3);
var vec2 = vec1.toImSortedSet(Integer::compare)
               .map(x -> x + 1)
               .toImList();

// Prove that it worked
assertEquals(vec(3, 4, 11),
             vec2);

Java streams originally required mutability. Paguro has its own sequence abstraction built in. It's similar to streams, but avoids mutation in place and doesn't expose anything mutable. I'm a little embarrassed to say that I never learned Streams properly for that reason. Here's a maybe not ideal Stream version:

var vec1 = vec(10, 2, 3);
var vec2 = xformArray(vec1.stream().sorted().map(x -> x + 1).toArray()).toImList();

// Prove that it worked
assertEquals(vec(3, 4, 11),
             vec2);

I should really make some Collector implementations of the Paguro collections if they will fit the latest API, or maybe make them fit it. Thanks for pointing that out.

The methods in StaticImports provide shorthand for constructing immutable collections and for turning various Java things into immutable Paguro ones.

If you use Paguro with an ide like IntelliJ IDEA (or maybe Eclipse), it's easier to see what methods are available when you type a dot. Or you could look at Transformable

Thanks for your interest. I hope your book is going well. I see you have new chapters!