Java集合去重的几种方法
2019-04-26 本文已影响12人
爱宝宝n
一、基础数据类型集合去重:
例: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 + "]");
}
二、对象根据指定属性去重
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;
}