简体   繁体   中英

java 8 collectors for streams with generics

I have a class with long field (primitive type):

class Transfer {
       private long id;
       //gets sets
}

I want to get a List<Long> from Collection<Transfer> which would contain all ids from Collection<Transfer> eg

Collection<Transfer> transfers = ..;
List<Long> ids = (List<Long>) transfers.stream().map(f -> f.getId()).collect(Collectors.toList());

The thing which confuses me is this ugly cast:

(List<Long>) transfers.stream()

Is there any way to avoid it?

Assuming that your getId() method return type is long or Long , this cast is absolutely unnecessary. You can write

List<Long> ids = transfers.stream().map(f -> f.getId()).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM