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

  1. LinkedHashSet去重
    去重后保持原有顺序(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};   
Collection noDups = new LinkedHashSet(Arrays.asList(arr));   
System.out.println("(LinkedHashSet) distinct words:    " + noDups); 
  1. HashSet去重方法一
    去重后顺序打乱(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
Collection noDups = new HashSet(Arrays.asList(arr));   
System.out.println("(HashSet) distinct words:    " + noDups);   
  1. HashSet去重方法二
    去重后顺序打乱(重复数据只保留一条)
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
Set s = new HashSet();   
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 uniques = new HashSet();   
Set dups = new HashSet();   
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); 

你可能感兴趣的:(18,java HashSet 去重复的4种方法)