zoukankan      html  css  js  c++  java
  • 使用 Java 删除 ArrayList 中的重复元素

    使用 Java 删除 ArrayList 中的重复元素
    1. 使用 Iterator

    import java.util.*;
    
    public class Test {
    	public static <T> List<T> removeDuplicates(List<T> list) {
    		List<T> newList = new ArrayList<T>();
    		for (T element : list) {
    			if (!newList.contains(element)) {
    				newList.add(element);
    			}
    		}
    		return newList;
    	}
    
    	public static void main(String args[]) {
    		List<Integer> list = new ArrayList<>(Arrays.asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5));
    		System.out.println("ArrayList with duplicates: " + list);
    		List<Integer> newList = removeDuplicates(list);
    		System.out.println("ArrayList with duplicates removed: " + newList);
    	}
    }
    

    ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5]
    ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]

    2. 使用 LinkedHashSet

    import java.util.*;
    
    public class Test {
    	public static <T> List<T> removeDuplicates(List<T> list) {
    		Set<T> set = new LinkedHashSet<>();
    		set.addAll(list);
    		list.clear();
    		list.addAll(set);
    		return list;
    	}
    
    	public static void main(String args[]) {
    		List<Integer> list = new ArrayList<>(Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
    		System.out.println("ArrayList with duplicates: " + list);
    		List<Integer> newList = removeDuplicates(list);
    		System.out.println("ArrayList with duplicates removed: " + newList);
    	}
    }
    

    ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]
    ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]

    3. 使用 Java 8 Stream.distinct()

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class Test {
    	public static void main(String[] args) {
    		List<Integer> list = new ArrayList<>(Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
    		System.out.println("ArrayList with duplicates: " + list);
    		List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
    		System.out.println("ArrayList with duplicates removed: " + newList);
    	}
    }
    

    ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]
    ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]

  • 相关阅读:
    BZOJ1717: [Usaco2006 Dec]Milk Patterns 产奶的模式
    BZOJ1031: [JSOI2007]字符加密Cipher
    关于后缀数组的实现
    BZOJ1692: [Usaco2007 Dec]队列变换
    BZOJ1725: [Usaco2006 Nov]Corn Fields牧场的安排
    POJ 2386 Lake Counting(搜索联通块)
    POJ 2386 Lake Counting(搜索联通块)
    Java演示设计模式中的写代码的代码
    Java演示设计模式中的写代码的代码
    源码映射
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10490540.html
Copyright © 2011-2022 走看看