代码如下
public class ListDuplicate {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("hello");
list.add("world");
System.out.println(getDuplicateElements(list.stream()));
}
public static <T> List<T> getDuplicateElements(Stream<T> stream) {
return stream
.collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
.entrySet().stream() // Set<Entry>转换为Stream<Entry>
.filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
}
执行结果如下:
[hello]
由于在方法中使用了泛型,所以可以接收任意类型的流,注意在如果是对象,别忘了重写其 hashCode() 和 equals() 方法。