Sobes.tech
Junior — Middle

How can you extract only unique objects from a data stream in the Stream API?

sobes.tech AI

Answer from AI

In Java Stream API, the distinct() method is used to extract unique objects from a stream. It returns a new stream with duplicates removed based on the equals() and hashCode() methods of the objects.

Example:

List<String> list = Arrays.asList("apple", "banana", "apple", "orange");
List<String> uniqueList = list.stream()
    .distinct()
    .collect(Collectors.toList());

System.out.println(uniqueList); // [apple, banana, orange]

If the objects are complex and you need uniqueness based on a specific field, you can use Collectors.toMap or filter with auxiliary structures, but for simple cases, distinct() is the easiest way.