对于List和普通数组元素怎么去重的方法

首先在处理之前需要明确一个事情,在当前场景下List或者普通数组中的元素如果是自定义对象那么就需要重写对象的equals方法和hashCode方法。

对于List的处理

方法1,通过Set实现类包裹一层返回,缺点是会打乱原有集合的顺序

public static <T> List<T> listRepeatUseSet(List<T> list){
    HashSet<T> hashSet = new HashSet<>(list);
    return new ArrayList<>(hashSet);
}

 方法2,新建一个新的List集合,这里不能指定大小因为当前传递过来的集合是有重复的所以长度大小是不正确的。

public static <T> List<T> listRepeatUseIteration(List<T> list){
    List<T> arrayList = new ArrayList<>();
    ListIterator<T> listIterator = list.listIterator();
    while (listIterator.hasNext()) {
        T next = listIterator.next();
        if(!arrayList.contains(next)){
            arrayList.add(next);
        }
    }
    return arrayList;
}

 方法3,在JDK8中可以通过流的方式使用collect收集方法收集成Set集合转换成流收集成List集合

ArrayList<Integer> arrayList = new ArrayList<>();
Integer[] integers={1,2,5,4,5,7,8,9,5,4,7,1,2,3,8,5,7};
Collections.addAll(arrayList,integers);
Set<Integer> collect = arrayList.stream().collect(Collectors.toSet());
ArrayList<Integer> collect1 = collect.stream().collect(Collectors.toCollection(ArrayList::new));
System.out.println(collect1);

 其实第三种方式有点多余,操作好像兜了一圈那样,并且IDEA中也提示可以使用集合Set具体集合类来初始化完成;但是如果面试时候或者别人问到,总要回答地出来吧。

对于数组的处理

如果是对象类型或者包装类型可以使用下面方法,

Integer[] arr={78,52,41,36,25,63,52,45,85,62,25};
HashSet<Integer> hashSet = new HashSet<>();
Collections.addAll(hashSet,arr);
//注意这里的size值需要使用hashSet的,不能使用原来的arr
Integer[] integers = hashSet.toArray(new Integer[hashSet.size()]);
System.out.println(Arrays.toString(integers));

 

JDK8之后还可以使用流的方式去重

Integer[] arr={78,52,41,36,25,63,52,45,85,62,25};
Integer[] integers = Arrays.stream(arr).distinct().toArray(Integer[]::new);
System.out.println(Arrays.toString(integers));

但是如果是基本数据类型,那么只能使用循环遍历判断了或者是在JDK8中使用stream流,jdk8中提供int、double、long的基本数据类型的stream流

int[] arr={78,52,41,36,25,63,52,45,85,62,25};
int[] ints = Arrays.stream(arr).distinct().toArray();
System.out.println(Arrays.toString(ints));

 

posted @ 2020-02-08 23:40  ALonely  阅读(736)  评论(0编辑  收藏  举报