基于基础类型的 List 去除重复数据

293 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

基于基础类型的 List 去除重复数据

Java 中基于基础类型的 ArrayList 去除重复数据方法。 注意:元素是对象的需要**重写对象的 hashcode()equals() 方法才能去重。

LinkedHashSet 进行 List 去重

LinkedHashSet 是一个删除 ArrayList 中重复数据最佳的方法,其内部做了两件事:

  • 删除重复数据
  • 保持添加的数据的顺序

在示例中,numbersList是包含整数的arrayList,其中有重复的数字;将列表添加到LinkedHashSet,然后将内容返回到列表中。返回结果arrayList没有重复的整数。

public static void main(String[] args) {
	int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
    LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(List);
    ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
    System.out.println(listWithoutDuplicates);
}

结果

[1, 2, 3, 4, 5, 6, 7, 8]

Java8 新特性 stream 进行 List 去重

使用 Java 8 stream api,steam 的 distinct() 方法返回一个由不同数据组成的流,通过对象的 equals() 方法进行比较。

然后使用 Collectors.toList() 方法收集所有区域数据 List。

用于在不使用 Set 的情况下 List 中删除重复项。

public static void main(String[] args){
	int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
    List<Integer> listWithoutDuplicates = List.stream().distinct().collect(Collectors.toList());
    System.out.println(listWithoutDuplicates);
} 

结果

[1, 2, 3, 4, 5, 6, 7, 8]

HashSet 不存储重复数据特性进行 List 去重

HashSet 不能添加重复数据的特性。 但是 HashSet ==不能保证添加顺序==,所以只能作为判断条件保证顺序。

  • 不需要保证顺序方式:

    private static List<String> removeSame(List<String> list) {
    	Set<String> set = new HashSet<>(list.size());
    	set.addAll(list);
    	List<String> result = new ArrayList<>();
    	for(String s : set){
    		result.add(s);
    	}
    	return result;
    }
    
  • 需要保证顺序方式:

    private static List<String> removeSame(List<String> list) {
    	Set<String> set = new HashSet<>(list.size());
    	List<String> result = new ArrayList<>(list.size());
    	for(String s : list){
    		if(set.add(s)) {
    			result.add(s);
    		}
    	}
    	return result;
    }
    

List 的 contains 方法循环遍历去重

List 循环遍历使用 contains 方法判断元素是否存在来实现只添加一次数据以避免重复。

private static List<String> removeSame(List<String> list) {
    List<String> result = new ArrayList<String>(list.size());
    for (String str : list) {
        if (!result.contains(str)) {
            result.add(str);
        }
    }
    return result;
}