Sobes.tech
Junior — Middle

Explain the purpose of the distinct() method and in what cases it is used when working with collections.

sobes.tech AI

Answer from AI

The distinct() method in Java is used to remove duplicates from a data stream (Stream). It returns a new stream containing only unique elements, preserving the order of their first appearance.

Most often, distinct() is applied when you need to obtain a set of unique values from a collection or the result of computations, for example, to remove repeated elements before further processing.

Example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DistinctExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
        List<Integer> uniqueNumbers = numbers.stream()
                                           .distinct()
                                           .collect(Collectors.toList());
        System.out.println(uniqueNumbers); // [1, 2, 3, 4, 5]
    }
}

Thus, distinct() helps to eliminate duplicates and obtain a clean dataset.

Explain the purpose of the distinct() method and in… - sobes.tech