How to use collect call in Java 8? -


lets have boring piece of code had use:

arraylist<long> ids = new arraylist<long>(); (myobj obj : mylist){     ids.add(obj.getid()); } 

after switching java 8, ide telling me can replace code collect call, , auto-generates:

arraylist<long> ids = mylist.stream().map(myobj::getid).collect(collectors.tolist()); 

however giving me error:

collect(java.util.stream.collector<? super java.lang.long,a,r>) in steam cannot  applied to: (java.util.stream.collector<t>, capture<?>, java.util.list<t>>) 

i tried casting parameter giving me undefined a , r, , ide isn't giving more suggestions.

i'm curious how can use collect call in scenario, , couldn't find information guide me properly. can shed light?

the issue collectors.tolist, not surprisingly, returns list<t>. not arraylist.

list<long> ids = remove.stream()         .map(myobj::getid)         .collect(collectors.tolist()); 

program interface.

from documentation:

returns collector accumulates input elements new list. there no guarantees on type, mutability, serializability, or thread-safety of list returned; if more control on returned list required, use tocollection(supplier).

emphasis mine - cannot assume list returned mutable, let alone of specific class. if want arraylist:

arraylist<long> ids = remove.stream()         .map(myobj::getid)         .collect(collectors.tocollection(arraylist::new)); 

note also, customary use import static java 8 stream api adding:

import static java.util.stream.collectors.tocollection; 

(i hate starred import static, nothing pollute namespace , add confusion. selective import static, java 8 utility classes, can reduce redundant code)

would result in:

arraylist<long> ids = remove.stream()         .map(myobj::getid)         .collect(tocollection(arraylist::new)); 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -