Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check elements count and throw an exception in the middle of the stream?

I have a stream of elements and want to get only one element from stream and throw exceptions if there are more than one element in the stream and if there is no elemenets at all. Is it possible to make with Stream?

public Entity getEntityByValue(String value) {
        return entityService.getEntitiesByValue(value)
                .stream
                // check here count of entities and throw a MultiMatchException if more than one entity is present
                .findAny()
                .orElseThrow(() -> throw NoEntitiesFoundException()); //no entities found
    }

I thought of using .reduce(a, b -> throw MultiMatchException) and throw the exception if the second element is exists but couldn’t combine it with other code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using collect()

stream.collect(Collectors.toMap(t -> 1, t -> t))
      .computeIfAbsent(1, t -> { throw new RuntimeException();});

Try it with:

Stream.of()...

Producing:

|  Exception java.lang.RuntimeException
|        at lambda$do_it$$2 (#16:1)
|        at HashMap.computeIfAbsent (HashMap.java:1228)
|        at (#16:1)

With:

Stream.of(1)...

Producing:

1

With:

Stream.of(1, 2)...

Producing:

|  Exception java.lang.IllegalStateException: Duplicate key 1 (attempted merging values 1 and 2)
|        at Collectors.duplicateKeyException (Collectors.java:135)
|        at Collectors.lambda$uniqKeysMapAccumulator$1 (Collectors.java:182)
|        at ReduceOps$3ReducingSink.accept (ReduceOps.java:169)
|        at Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:1006)
|        at AbstractPipeline.copyInto (AbstractPipeline.java:509)
|        at AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:499)
|        at ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:921)
|        at AbstractPipeline.evaluate (AbstractPipeline.java:234)
|        at ReferencePipeline.collect (ReferencePipeline.java:682)
|        at (#13:1)

Using reduce()

Same approach:

stream.reduce((i1, i2) -> { throw new RuntimeException(); })
      .orElseThrow(() -> new RuntimeException());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading