更新时间:2021-06-02 12:20:59 来源:极悦 浏览3949次
1.基础数据类型集合去重:
例:String
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("c");
list.add("c");
list.add("a");
list.add("a");
list.add("b");
//1.set集合去重,不改变原有的顺序
pastLeep1(list);
//2.遍历后判断赋给另一个list集合 不改变原有的顺序
pastLeep2(list);
//3.set去重 并按自然顺序排序
pastLeep3(list);
//4.set去重(缩减为一行)
pastLeep4(list);
//5.去重并按自然顺序排序
pastLeep5(list);
}
方法实现:
//1.set集合去重,不改变原有的顺序
public static void pastLeep1(List<String> list){
System.out.println("list = [" + list.toString() + "]");
List<String> listNew=new ArrayList<>();
Set set=new HashSet();
for (String str:list) {
if(set.add(str)){
listNew.add(str);
}
}
System.out.println("listNew = [" + listNew.toString() + "]");
}
//2.遍历后判断赋给另一个list集合 不改变原有的顺序
public static void pastLeep2(List<String> list){
System.out.println("list = [" + list.toString() + "]");
List<String> listNew=new ArrayList<>();
for (String str:list) {
if(!listNew.contains(str)){
listNew.add(str);
}
}
System.out.println("listNew = [" + listNew.toString() + "]");
}
//3.set去重 并按自然顺序排序
public static void pastLeep3(List<String> list){
System.out.println("list = [" + list + "]");
Set set = new HashSet();
List<String> listNew=new ArrayList<>();
set.addAll(list);
listNew.addAll(set);
System.out.println("listNew = [" + listNew + "]");
}
//4.set去重(缩减为一行) 并按自然顺序排序
public static void pastLeep4(List<String> list){
System.out.println("list = [" + list + "]");
List<String> listNew=new ArrayList<>(new HashSet(list));
System.out.println("listNew = [" + listNew + "]");
}
//5.去重并按自然顺序排序
public static void pastLeep5(List<String> list){
System.out.println("list = [" + list + "]");
List<String> listNew=new ArrayList<>(new TreeSet<String>(list));
System.out.println("listNew = [" + listNew + "]");
}
2.对象根据指定属性去重
List<User>userList = new ArrayList<>();
userList.add(new User(1,"小李","男"));
userList.add(new User(5,"小李","男"));
userList.add(new User(7,"小李","男"));
userList.add(new User(3,"小李","男"));
userList.add(new User(1,"小李","男"));
userList.add(new User(5,"小李","男"));
//6.对象 根据指定属性去重 并按自然顺序排序
System.out.println(removeDuplicateUser(userList));
//7. 根据指定属性去重 并按自然顺序排序2
System.out.println(removeDuplicateUser2(userList));
//6.对象 根据指定属性去重 并按自然顺序排序
public static ArrayList<User> removeDuplicateUser(List<User> users) {
Set<User> set = new TreeSet<User>(new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return new Integer(o1.getId()).compareTo(new Integer(o2.getId()));
}
});
set.addAll(users);
return new ArrayList<User>(set);
}
//7. 根据指定属性去重 并按自然顺序排序2
public static List<User> removeDuplicateUser2(List<User> list){
List<User> unique = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(User::getId))), ArrayList::new)
);
return unique;
}
以上就是极悦小编介绍的"Java集合去重的几种方法",希望对大家有帮助,如有疑问,请在线咨询,有专业老师随时为您服务。
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习