Klavy Dev :
I have a set containing Item objects: Set<Item>
The class Item has a method getName()
that returns a string. I want to convert Set<Item>
to Set<String>
using the method Item#getName()
Any better way, rather than using forEach ?
Fritz Duchardt :
itemSet.stream().map(Item::getName).collect(Collectors.toSet())
Explaining this method-chain using Java Stream:
- The
.stream
pulls each item from your set, one after another. See this article published by Oracle, Processing Data with Java SE 8 Streams, Part 1. - The
.map
calls the specified method (getName
) on each object streaming from your set. The output of this is each item’s name property, apparently aString
object in your scheme. - The
.collect
captures each of those name outputs, and puts them into a freshSet
object. This newSet
is returned when this code completes.