i didn't know how formulate title of question, i'll jump example.
let's want iterate on list of elements, , based on conditions, add said element new list.
here create method wants check if item exclusive first list (isn't present in second one). know particular silly example solve using sets, i'm trying illustrate case pop up
public list<item> newitems(list<item> items, list<item> otheritems) { list<item> newitems = new arraylist<>(); (item i: items) { (item j: otheritems) { if (i.equals(j)) //missing code } newitems.add(i); } return newitems; }
so here want add current item i
newitems
if not equal single item in otheritems
. first impulse put break;
says //missing code
, break out of first loop , not impede adding of i
newitems
.
i aware of correct solution use boolean variable consistently check truth of if statement, , add item i
newitems
based on it's truth value @ end of second loop. this:
for (item i: items) { boolean check = true; (item j: otheritems) { if (i.equals(j)) check = false; break; //to avoid unnecessary iterations } if (check) newitems.add(i); }
this seems incredibly bulky , quite redundant however. there more efficient , elegant way of doing this?
if understand question correctly, need create list, collected items items
excluding items present in both items
, otheritems
. if yes, can list#removeall()
:
public list<item> newitems(list<item> items, list<item> otheritems) { list<item> res = new arraylist<>(items); // create copy of items res.removeall(otheritems); // remove items presented in otheritems return res; }
if there other condition(s) exclude items, use stream, filter(s) , collector, follows:
return items.stream() .filter(i -> !otheritems.contains(i)) .filter( /* condition */ ) .collect(collectors.tolist());
Comments
Post a Comment