Using Java lambdas or streams to convert list of POJOs into a list of their IDs

  • A+
Category:Languages

I'm trying to broaden my Java horizons and start actually writing Java 8+ code. I have a situation where I have a list of POJOs (each POJO instancehas an id : Long field) and I need to produce a List<Long> representing all of their ids. Here's my code that works perfectly fine:

List<Fizzbuzz> fizzbuzzes = getFizzbuzzes(); List<Long> fbIds = new ArrayList<>(); for(Fizzbuzz fb : fizzbuzzes) {     fbIds.add(fb.getId()); } 

I'm wondering if there's a more "modern" Java 8+ way (lambdas or collections tricks, streaming, etc.) to write this code. Any ideas or is this as good as it gets?

 


  • Stream the list of Fizzbuzz
  • map this stream to a Stream<Long>
  • and finally collect it into a List<Long>.

It would give :

List<Long> fbIds = getFizzbuzzes().stream()                                   .map(Fizzbuzz::getId)                                   .collect(Collectors.toList()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: