• Index

去重Stream

Last updated: ... / Reads: 32 Edit

要在Stream中去除重复的元素,您可以使用Stream.distinct()方法。distinct()方法会返回一个新的Stream,其中包含原始Stream中的唯一元素。

以下是一个示例:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 2, 1);
List<Integer> distinctNumbers = numbers.stream()
        .distinct()
        .collect(Collectors.toList());

在这个示例中,我们首先创建了一个包含整数的列表,其中包含重复的元素。然后,我们使用stream()方法创建一个Stream,并使用distinct()方法去除重复的元素。最后,我们使用collect()方法将去重后的元素收集到一个新的列表中。

请注意,distinct()方法使用equals()方法来判断元素是否相等。因此,如果您的元素类没有实现equals()方法,或者您希望使用自定义的相等性比较逻辑,您可以在distinct()方法之前使用Stream.map()方法来转换元素。 以下是一个使用自定义相等性比较逻辑的示例:

List<String> words = Arrays.asList("apple", "banana", "APPLE", "Banana");
List<String> distinctWords = words.stream()
        .map(String::toLowerCase)
        .distinct()
        .collect(Collectors.toList());

在这个示例中,我们首先创建了一个包含字符串的列表,其中包含大小写不同的相同单词。然后,我们使用stream()方法创建一个Stream,并使用map()方法将所有单词转换为小写。最后,我们使用distinct()方法去除重复的单词,并使用collect()方法将去重后的单词收集到一个新的列表中。


Comments

Make a comment

  • Index