Is there an idiomatic way to assert a stream has only one element while yielding that element?

Viewed 285

Starting with this code:

public Thing thereCanBeOnlyOne(Stream<Thing> stream) {
  List<Thing> things = stream.collect(Collectors.toList());  
  if(things.size() != 1) {
    throw new IllegalArgumentException();
  }
  return things.get(0);
}

Is there a more succint way to express the method body?

What I tried so far:

I read the documentation for Collector and reduce, but didn't find anything.

2 Answers

If using Guava is palatable to you, use MoreCollectors.onlyElement:

public Thing thereCanBeOnlyOne(Stream<Thing> stream) {
  return stream.collect(MoreCollectors.onlyElement());
}

Equivalents may well exist in other common libraries; I am just familiar with Guava.

How about

public static Thing thereCanBeOnlyOne(Stream<Thing> stream) {
    Object[] array = null;
    if((array = stream.limit(2).toArray()).length != 1) {
            throw new IllegalArgumentException();
    }
    return (Thing)array[0];
}

To me it seems like less overhead.

Related