Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Paguro with Java stream? #43

Closed
viebel opened this issue May 10, 2021 · 1 comment
Closed

How to use Paguro with Java stream? #43

viebel opened this issue May 10, 2021 · 1 comment
Labels

Comments

@viebel
Copy link

viebel commented May 10, 2021

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
Copy link
Owner

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants