18,java HashSet 去重复的4种方法

  1. LinkedHashSet去重
    去重后保持原有顺序(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};   
Collection<string> noDups = new LinkedHashSet<string>(Arrays.asList(arr));   
System.out.println("(LinkedHashSet) distinct words:    " + noDups); 
  1. HashSet去重方法一
    去重后顺序打乱(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
Collection<string> noDups = new HashSet<string>(Arrays.asList(arr));   
System.out.println("(HashSet) distinct words:    " + noDups);   
  1. HashSet去重方法二
    去重后顺序打乱(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
Set<string> s = new HashSet<string>();   
for (String a : arr)   
{   
 if (!s.add(a))   
 {   
 System.out.println("Duplicate detected: " + a);   
 }   
}   
System.out.println(s.size() + " distinct words: " + s); 
  1. HashSet去重方法三
    去重后顺序打乱(相同的数据一条都不保留,取唯一)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
Set<string> uniques = new HashSet<string>();   
Set<string> dups = new HashSet<string>();   
for (String a : arr)   
{   
 {   
 if (!uniques.add(a))   
 dups.add(a);   
 }   
}   
uniques.removeAll(dups);   
System.out.println("Unique words:    " + uniques);   
System.out.println("Duplicate words: " + dups); 
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Java集合类可用于存储数量不等的对象,并可以实现常用的数据结构如栈,队列等,Java集合还可以用于保存具有映射关...
    小徐andorid阅读 5,952评论 0 13
  • 一、集合入门总结 集合框架: Java中的集合框架大类可分为Collection和Map;两者的区别: 1、Col...
    程序员欧阳阅读 13,986评论 2 61
  • 第十一章 持有对象 Java实用类库还提供了一套相当完整的容器类来解决这个问题,其中基本的类型是List、Set、...
    Lisy_阅读 4,272评论 0 1
  • 集合类框架的介绍: ![Java 集合类框架](https://upload-images.jianshu.io/...
    LynnGuo阅读 4,071评论 0 1
  • 在编程中,常常需要集中存放多个数据。集合类主要负责保存、盛装其他数据,因此集合类也被称为容器类。所有的集合类都位于...
    一一一二二三阅读 3,106评论 0 1