Java 8 use streams for a "group by" feature
Thank you for a nicely formulated and formatted first question! :)

Indeed, the same result can be achieved with much less code using Java 8.

I suggest the following:


Group all the items into a Map&lt;String, List&lt;Item&gt;&gt;, equivalent of the first original for loop:

Map&lt;String, List&lt;Item&gt;&gt; itemsGroupedByCode = 
  items.stream().collect(Collectors.groupingBy(Item::getCode));

Collect all the messages citing duplicate entries, equivalent of the second original for loop, but without the prefix:

String duplicatesMessage =
  itemsGroupedByCode.entrySet().stream()
      .filter(entry -&gt; entry.getValue().size() &gt; 1)
      .map(entry -&gt; {
        final String duplicateValues = entry.getValue().stream()
                                                       .map(Item::getDescription)
                                                       .collect(Collectors.joining(", ", "{", "}"));
        return String.format("'%1$s' used by %2$s", entry.getKey(), duplicateValues);
  }).collect(Collectors.joining(", "));

Return the result, empty if there were no duplicates or prefixed if there were some entries:

if (!duplicatesMessage.isEmpty()) {
  return "Some of the items are sharing the same code: " + duplicatesMessage;
}
return "";



I'd also suggest to change the return type of the method to Optional&lt;String&gt; and return Optional.empty() instead of the empty string. But this is up to you to decide if it fits the context of your app.