list中是否有重复元素,并取出重复的元素
一、String list中是否有重复元素
public static void main(String[] args) {
List<String> stringList=new ArrayList<>(Arrays.asList("a","a","b","c"));
long count = stringList.stream().distinct().count();
if (stringList.size() == count) {
System.out.println("没有重复元素");
} else {
System.out.println("有重复元素");
}
}
二、取出String list中重复的元素
List<String> telephoneList = new ArrayList<>();
//字符串取出重复值
List<String> repeatList = telephoneList.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey).collect(Collectors.toList());
三、list去重 (根据单位id去重)
//根据单位id去重,取出不重复的单位列表
static List<Dept> distinctDeptList(List<Dept> deptList){
List<Dept> distinctList = deptList.stream().collect(
collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Dept::getDeptId))), ArrayList::new)
);
return distinctList;
}
四、list取出重复的单位id列表
//取出重复的单位列表
static List<String> repeatDeptList(List<Dept> deptList){
List<String> repeatList = deptList.stream().collect(Collectors.groupingBy(Dept::getDeptId, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey).collect(Collectors.toList());
return repeatList;
}
参考文档:
https://www.cnblogs.com/debugginging/p/13163813.html
https://www.cnblogs.com/cchilei/p/14831293.html