google / mug

A small Java 8 library (string manipulation, stream utils)
Apache License 2.0
367 stars 65 forks source link

BiStream equivalent to Stream.findFirst()? #5

Closed andrewparmet closed 7 years ago

andrewparmet commented 7 years ago

Is there an equivalent to findFirst() that can return an Optional<Entry<K,V>> or a reason that such a method is not included? The workaround I'm using is limit(1).toMap() followed by an Iterables.getOnlyElement(map.entrySet()) but it'd be nice if this was built in!

Thanks for a great library.

fluentfuture commented 7 years ago

Thanks for the interest in the library!

One design goal of this library is to avoid forcing users to explicitly go through any semantic-anemic types.

While Map.Entry isn't that bad, it has setValue(), which makes it mutable.

Instead, my opinionated objective is to have the users map() to their own type at the proper abstraction layer, rather than having to go through some "generic" type as the middle-man.

For example: biStream.map(MyOwnType::new).findFirst().

That said, you may not have a MyOwnType and Map.Entry could be good enough sometimes. I vaguely recall once considering something along this line, but then figured that it should be easy enough for the user to do:

biStream.map(AbstractMap.SimpleEntry<K, V>::new).findFirst()

I don't remember if that <K, V> is necessary or the compiler is able to infer.

Let me know if this works for you?

andrewparmet commented 7 years ago

Ironically enough I just tried to work through that in my own code and got hung up at setValue() myself - and proceeded to roll my own type. It works nicely. Thanks!