java8的方法中可以找出相同的元素 代码如下:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("a");
list.add("b");
System.out.println(getDuplicateElements(list.stream()));
}
public static <T> List<T> getDuplicateElements(Stream<T> stream) {
return stream.collect(Collectors.groupingBy(p -> p,Collectors.counting()))
.entrySet().stream() // Set<Entry>转换为Stream<Entry>
.filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
运行结果如下:
[a, b]
;