在 Java 8 中如何查找流中的重复项并从流中删除重复项

使用 Stream.distinct() 删除重复项

distinct()方法返回由给定流的不同元素组成的流。
根据元素的 equals()方法检查元素是否相等。

// 包含重复元素的 ArrayList
ArrayList<Integer> numbersList 
	= new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));

List<Integer> listWithoutDuplicates = numbersList.stream()
			.distinct()
			.collect(Collectors.toList());

System.out.println(listWithoutDuplicates);

Collectors.toMap() 计算出现次数

有时,我们有兴趣找出所有元素是重复的以及它们在原始列表中出现的次数。
我们可以使用Map来存储这些信息。

我们必须遍历列表,将元素作为映射键,并将其所有出现在映射值字段中。

// 包含重复元素的 ArrayList
ArrayList<Integer> numbersList 
	= new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));

Map<Integer, Long> elementCountMap = numbersList.stream()
    		.collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));

System.out.println(elementCountMap);
欢迎来到之路教程(on itroad-com)

使用 Collectors.toSet() 删除重复项

另一种简单且非常有用的方法是将所有元素存储在一个 Set中。
根据定义,集合只存储不同的元素。

// 包含重复元素的 ArrayList
ArrayList<Integer> numbersList 
	= new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));

Set<Integer> setWithoutDuplicates = numbersList.stream()
			.collect(Collectors.toSet());

System.out.println(setWithoutDuplicates);
日期:2020-09-17 00:10:06 来源:oir作者:oir