google / guava

Google core libraries for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Immutable*Array.toImmutable*Array() collector methods

JanecekPetr opened this issue · comments

Please consider adding:

  • ImmutableIntArray.toImmutableIntArray()
  • ImmutableLongArray.toImmutableLongArray()
  • ImmutableDoubleArray.toImmutableDoubleArray()

collector methods for streams. Yes, it is possible to use the already efficient ImmutableLongArray.copyOf(stream), so this would be a small convenience. It just feels much more natural to work with streams and then collect them into a immutable container rather than holding streams and copying from them.

Hey there!!
This idea sounds interesting.Can you please elaborate as to how these methods would be better alternatives than the existing ones.

No, it was misinformed, I don't know what I was thinking. Here's what we have today:

ImmutableIntArray intArrayCollectViaCopyOf = ImmutableIntArray.copyOf(IntStream.empty());

...this doesn't flow nicely, so if you have a long chain of stream transformations that end up with an IntStream, you'll need to store it in a local variable and call ImmutableIntArray.copyOf(intStream). That's obviously not bad at all, it's the best option right now and for the future.

There's an alternative:

ImmutableIntArray intArrayCollectViaBuilder = IntStream.empty()
    .collect(ImmutableIntArray::builder, Builder::add, (left, right) -> left.addAll(right.build()))
    .build();

...this nicely flows from an IntStream, so if you have a long chain of stream transformations that end up with an IntStream, it seemingly fits. But it's long, bad, and much more expensive than the method above.

What I thought we could do by adding new collector methods, and we obviously cannot, is this:

ImmutableIntArray intArrayCollect = IntStream.empty()
    .collect(ImmutableIntArray.toImmutableIntArray);

...that'd be nice. But it cannot be done. There is no IntCollector interface, there is no IntStream.collect(...) method taking a single argument.

Please call people out on bogus wishes, or close the tickets immediately :)

(Maybe I wanted

ImmutableIntArray intArray = Stream.of(1, 2, 3)
    .collect(ImmutableIntArray.toImmutableIntArray());

which would promote using ImmutableIntArray as a default type instead of List<Integer> so in that light that'd be very good. It is also something we cannot currently do with a copyOf(), so we're either converting to IntStreams or doing

List<Integer> listOfIntegers = Stream.of(1, 2, 3).toList();
ImmutableIntArray intArray = ImmutableIntArray.copyOf(listOfIntegers);

I still think the improvement would make ImmutableIntArray an interesting type to use by default when using ints, but the upside is very small. If Guava was still actively adding new stuff, maybe. In the current state, though, it's hardly worth considering.