Roma :
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());
}
}
Eran :
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 Stream
s 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());
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=329288&siteId=1