Java 8 - Streams Nested ForEach with different Collection -
i try understand new java 8 streams , tried days transfer nested foreach loops on collection in java 8 streams.
is possible refactor following nested foreach loops including if-conditions in java-8-streams?
if yes like.
arraylist<classinq> inq = new arraylist<>(); treemap<string, salesquot> quotations = new treemap<>(); arraylist<classinq> tempinqandquot = new arraylist<>(); arraylist<salesquot> tempquotpos = new arraylist<>(); (classinq siminq : this.inq){ if (!siminq.isclosed() && !siminq.isdenied()){ (map.entry<string, salesquot> quot: quotations.entryset()){ salesquot sapquot = quot.getvalue(); if (sapquot.getinquirydocumentnumber().compareto(siminq.getsapinquirynumber()) == 0){ siminq.setsapquotationnumber(sapquot.getquotationdocumentnumber()); tempinqandquot.add(siminq); (map.entry<string, salesquotposition> quotp : sapquot.getposition().entryset()){ tempquotpos.add(quotp.getvalue()); } } } } }
thanks lot help.
br
first, try adhere java naming conventions, upper case variable names make hard read code. second, it’s thing want learn stream
api should not ignore basics of pre-java 8 collection
apis.
it’s not useful iterate on entryset()
when interested in either, keys or values. 2 times within small piece of code.
at first appearance can replace
for (map.entry<string, salesquot> quot: quotations.entryset()){ salesquot sapquot = quot.getvalue();
with simpler
for (salesquot sapquot: quotations.values()){
at second, entire
for(map.entry<string,salesquotposition> quotp: sapquot.getposition().entryset()){ tempquotpos.add(quotp.getvalue()); }
can replaced by
tempquotpos.addall(sapquot.getposition().values());
thus without streams, code can simplified to
for (classinq siminq : this.inq){ if (!siminq.isclosed() && !siminq.isdenied()){ (salesquot sapquot: quotations.values()){ if (sapquot.getinquirydocumentnumber().compareto(siminq.getsapinquirynumber()) == 0){ siminq.setsapquotationnumber(sapquot.getquotationdocumentnumber()); tempinqandquot.add(siminq); tempquotpos.addall(sapquot.getposition().values()); } } } }
though it’s still not clear supposed , whether it’s correct. besides errors , suspicions named in comments question, modifying incoming values (esp. outer loop) not right.
it’s not clear why using ….compareto(…)==0
rather equals
.
however, can straight-forwardly rewritten use streams without changing of code’s logic:
this.inq.stream().filter(siminq -> !siminq.isclosed() && !siminq.isdenied()) .foreach(siminq -> quotations.values().stream().filter(sapquot -> sapquot.getinquirydocumentnumber().compareto(siminq.getsapinquirynumber())==0) .foreach(sapquot -> { siminq.setsapquotationnumber(sapquot.getquotationdocumentnumber()); tempinqandquot.add(siminq); tempquotpos.addall(sapquot.getposition().values()); }) );
still, recommend cleaning original logic first before rewriting using other apis. stream form benefit more precise definition of achieve.
Comments
Post a Comment