Changing values in Set<?>

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 a String object in your scheme.
  • The .collect captures each of those name outputs, and puts them into a fresh Set object. This new Set is returned when this code completes.

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115710&siteId=1