java list 快速去重 有序 重复 LinkedHashSet HashSet

r囧r小猫 2024-03-17 16:12 170阅读 0赞

如果list中装的是简单元素,int 类型,string类型,想要去重,并且保持在list中的顺序,最快的方式如下:

使用 LinkedHashSet,去重加有序。

使用 HashSet,只去重,但顺序任意。

  1. public static void t1(){
  2. List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 7, 8));
  3. System.out.println(list); //输出[10, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 7, 8]
  4. LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(list);
  5. List<Integer> distinct = new ArrayList<>(linkedHashSet);
  6. System.out.println(distinct); //输出[10, 1, 2, 3, 4, 5, 6, 7, 8]
  7. }
  8. public static void t2(){
  9. List<String> list = new ArrayList<>(Arrays.asList("张三","张三", "李四", "李四", "tom", "tom", "mike"));
  10. System.out.println(list); //[张三, 张三, 李四, 李四, tom, tom, mike]
  11. LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(list);
  12. List<String> distinct = new ArrayList<>(linkedHashSet);
  13. System.out.println(distinct); //[张三, 李四, tom, mike]
  14. }

参考

Java中List集合对象去重及按属性去重的8种方法_java list对象去重_//承续缘_纪录片的博客-CSDN博客

发表评论

表情:
评论列表 (有 0 条评论,170人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HashSet原理

    hashSet的实现原理: 往Haset添加元素的时候,HashSet会先调用元素的hashCode方法得到元素的哈希值 , 然后通过元素 的哈希值经过移位等运算,就可