To get distinct values from a list in Java, you can use the stream()
method of the List
interface and the distinct()
method of the Stream
interface.
Here's an example of how to use the stream()
and distinct()
methods to get distinct values from a list:
import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 3, 4, 4, 5); List<Integer> distinctNumbers = numbers.stream().distinct().collect(Collectors.toList()); System.out.println(distinctNumbers); // prints [1, 2, 3, 4, 5] } }Sow:ecruww.lautturi.com
In this example, a list of numbers is created with some duplicates. The stream()
method is called on the list to create a stream of the elements. The distinct()
method is then called on the stream to filter out the duplicates. The collect()
method is called on the stream to collect the elements back into a list. The resulting list of distinct numbers is then printed to the console.
You can use the stream()
and distinct()
methods with any type of list, as long as the type implements the equals()
and hashCode()
methods correctly.