awgtek awgtek - 14 days ago 4
Java Question

How to get mapped items of stream into a set

Not sure what's the best (most efficient, performant, and/or fewest characters needed, with preference to the fewest characters) way to effectively get the resulting set of a mapping using Java streams.

I.e. what would effectively replace:

Set<String> groupings = new HashSet<>();
for (Item item : items) {
groupings(item.getGrouping());
}
return groupings;


Should I use map(...) following by a distinct(...)? Looking for solutions to this.

Answer

I might have misunderstood you, but it could look like this:

Set<String> groupings = items.stream()
  .map(Item::getGrouping)
  .collect(Collectors.toSet())

Since the collector is a set, no duplicates will be allowed.