1

I have transformed a regular for loop code into java 8 streams. I tried a few, but i am still learning this and running out of ideas, please suggest ideas. can this be further simplified ? Other than using forEach, I am not able to change much. Also, why do I have to typecast the eid to String in getERecordFromId((String)eid)

Stream <String>eIdsStream = getEidStream();

final HashSet<String> declinedRecords = new HashSet<>();

eIdsStream.forEach (eid ->  {
        ERecord eRecord = getERecordFromId((String)eid);
        if(eRecord.getEHash() != null &&  Status.DECLINED == eRecord.getStatus()) {
            declineRecords.add(eRecord.getEHash());
        }
    }
2

1 Answer 1

6

The casting is required since you use a raw Stream variable. Assuming getEidStream() returns a Stream<String>, you should have assigned it to a Stream<String> variable, or not assigned it to a variable at all.

Using forEach defeats the purpose of using Streams in the first place.

You should use filter and map to transform the Stream to hold the required elements, and then collect to a Set.

Set<String> declinedRecords =
    getEidStream().map(eid -> getERecordFromId(eid))
                  .filter(eRecord -> eRecord.getEHash() != null &&  Status.DECLINED == eRecord.getStatus())
                  .map(ERecord::getEHash)
                  .collect(Collectors.toSet());
Sign up to request clarification or add additional context in comments.

9 Comments

And to answer your question about casting eid, it's because you have defined a Stream without specifying the generic parameter Stream<String>.
ok.. this makes sense. but I get compile error for eRecord.getEHash() and eRecord.getStatus() --- cannot resolve method and also ERecord::getEHash -- cannot access non static method as static
@Roma what kind of method is getEHash? Is it an instance method of ERecord or a static method of that class? The eRecord.getEHash() call in your question suggests it's an instance method. You can always replace it with a lambda expression if the method reference doesn't work (eRecord -> eRecord.getEHash())
it is an instance method of ERecord.
@Roma Does the code in your question pass compilation?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.