java List集合去重保持原顺序
-
LinkedHashSet去重,去重后保持原有顺序(重复数据只保留一条)
String[] arr = new String[] { "a", "c", "aa", "a", "b", "d" }; // 利用LinkedHashSet去重 Collection collection = new LinkedHashSet(Arrays.asList(arr)); System.out.println("(LinkedHashSet) distinct words: " + collection); // 转为list List list = new ArrayList(collection);
输出:
(LinkedHashSet) distinct words: [a, c, aa, b, d]
-
HashSet去重方法,去重后顺序打乱(重复数据只保留一条)
String[] arr = new String[] { "a", "c", "aa", "a", "b", "d" }; // 利用HashSet去重 HashSet h = new HashSet(Arrays.asList(arr)); System.out.println("(HashSet) distinct words: " + collection); // 转为list List list2 = new ArrayList(collection);
输出:
(HashSet) distinct words: [a, c, aa, b, d]