在流(Stream)中,distinct() 方法是用于去除流中重复元素的方法。当你调用 distinct() 方法时,它会返回一个包含原始流中不重复元素的新流。
下面是 distinct() 方法的一般用法:
Stream<T> distinct()
这里的 T 是流中元素的类型。调用 distinct() 方法后,它会使用元素的 equals() 方法来确定元素是否重复,然后返回一个新的流,其中不包含重复元素。
值得注意的是,distinct() 方法依赖于元素的 equals() 方法来判断是否重复,所以确保你的元素类正确实现了 equals() 方法以确保正确的去重行为。
下面是一个简单示例,展示了如何使用 distinct() 方法去除列表中的重复元素:
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana");
Stream<String> distinctElements = list.stream().distinct();
distinctElements.forEach(System.out::println);
在上面的示例中,通过将列表转换为流并调用 distinct() 方法,我们得到了一个包含不重复元素的新流,并通过 forEach 方法打印了这些不重复的元素。