LINQs Enumerable.Single () in Java 8 threads

I have some experience with C # LINQ and am trying to learn the Java 8 stream API. Now in LINQ, I regularly use the Single () Method , which selects the only and only object from the sequence and throws an exception if it is not the only object in the stream.

Now:

  • Am I correct that there is no such method in Java 8 threads?
  • Is there a preferred alternative to get this feature?
  • Is it a good idea to implement this yourself?
+4
source share
1 answer

Here is one way to get this functionality:

Stream<String> stream = Stream.of ("first");
String single = stream.reduce((a,b)->{throw new SomeException();})
                      .get();

, , reduce . , get() NoSuchElementException.

, , :

Stream<String> stream = Stream.of ("first");
String single = stream.reduce((a,b)->{throw new SomeException();})
                      .orElseThrow(SomeException::new);
+4

All Articles