Java教程

Java中List去重

本文主要是介绍Java中List去重,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Test {

	public static void main(String[] args) {
		
		List<String> list = new ArrayList<String>();
		
		list.add("1001A410000000PS6PI3");
		list.add("1001A410000000PS6WK7");
		list.add("1001A410000000PS6PI3");
		list.add("1001A410000000PS6W77");
		
		System.out.println(removeDuplicate1(list));
//		System.out.println(removeDuplicate2(list));
//		System.out.println(removeDuplicate3(list));
//		System.out.println(removeDuplicate4(list));
//		System.out.println(removeDuplicate5(list));
		 
	}

	/**
	 * 方法一: Stream 去重:list.stream().distinct()
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate1(List<String> list) {
		List<String> newList = (List) list.stream().distinct().collect(Collectors.toList());
		return newList;
	}
	
	/**
	 * 方法二:通过 HashSet 剔除重复元素(会改变原有顺序)
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate2(List<String> list) {
		Set<String> tempSet = new HashSet<String>(list);
		list.clear();
		list.addAll(tempSet);
		return list;
	}
	
	/**
	 * 方法三:删除 ArrayList 中重复元素,保持顺序
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate3(List<String> list) {
		
		Set<String> tempSet = new HashSet<String>();
		List<String> newList = new ArrayList<>();
		
		for (Iterator iter = list.iterator(); iter.hasNext(); ) {
	        String next = (String) iter.next();
	        if (tempSet.add(next)) {
	            newList.add(next);
	        }
	    }
		return newList;
	}
	
	/**
	 * 方法四:遍历 list,用 tempList.contain(),不存在 add
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate4(List<String> list) {
		List<String> tempList = new ArrayList<>();
		
		for (int i = 0; i < list.size(); i++) {
			if (!tempList.contains(list.get(i))) {
				tempList.add(list.get(i));
			}
		}
		return tempList;
	}
	
	/**
	 * 方法五:循环 list 中的所有元素然后删除重复(会改变原有顺序)
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate5(List<String> list) {
		for (int i = 0; i < list.size(); i++) {
	        for (int j = list.size() - 1; j > i; j--) {
	           if (list.get(i).equals(list.get(j))) {
	                list.remove(list.get(i));
	            }
	        }
	    }
		return list;
	}
}
这篇关于Java中List去重的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!