java - Creating a new collection from an existing collection -
i have collection of objects follows:
collection<foo> where foo is
public class foo { private user user; private item item; public foo(user user, item item) { this.user = user; this.item = item; } public user getuser() { return user; } public void setuser(user user) { this.user = user; } public item getitem() { return item; } public void setitem(item item) { this.item = item; } } i want return collection of type collection<item> using collection<foo>. using for loop , looping through collection, getting item, , adding new list. far have used google guava create collection<foo> using predicate.
is there method/function in google guava allow me create collection<item> collection<foo>? should use transform function?
if can use java 8:
collection<item> items = foos.stream() .map(foo::getitem) .collect(tolist()); otherwise can indeed use transform method. in case:
function<foo, item> f = new function<foo, item>() { public item apply(foo foo) { return foo.getitem(); } }; collection<item> items = collections2.transform(foos, f);
Comments
Post a Comment