- package com.huawei.test;
-
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.LinkedHashSet;
- import java.util.Set;
-
- public class FindDups
- {
-
-
-
-
-
- public static void findDup1(String[] arr)
- {
- Collection<string> noDups = new LinkedHashSet<string>(Arrays.asList(arr));
- System.out.println("(LinkedHashSet) distinct words: " + noDups);
- }
-
-
-
-
-
-
- public static void findDup2(String[] arr)
- {
- Collection<string> noDups = new HashSet<string>(Arrays.asList(arr));
- System.out.println("(HashSet) distinct words: " + noDups);
- }
-
-
-
-
-
-
- public static void findDup3(String[] arr)
- {
- 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);
-
- }
-
-
-
-
-
-
- public static void findDup4(String[] arr)
- {
- 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);
- }
-
-
-
-
-
- public static void main(String[] args)
- {
- String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
- findDup1(arr);
- findDup2(arr);
- findDup3(arr);
- findDup4(arr);
- }
- }
package com.huawei.test;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class FindDups
{
/**
* 去重1(重复数据只保留一条)
* 去重后保持原有顺序
* @param arr 数组
*/
public static void findDup1(String[] arr)
{
Collection<string> noDups = new LinkedHashSet<string>(Arrays.asList(arr));
System.out.println("(LinkedHashSet) distinct words: " + noDups);
}
/**
* 去重2(重复数据只保留一条)
* 去重后顺序打乱
* @param arr 数组
*/
public static void findDup2(String[] arr)
{
Collection<string> noDups = new HashSet<string>(Arrays.asList(arr));
System.out.println("(HashSet) distinct words: " + noDups);
}
/**
* 去重3(重复数据只保留一条)
* 去重后顺序打乱
* @param arr 数组
*/
public static void findDup3(String[] arr)
{
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);
}
/**
* 去重4(相同的数据一条都不保留,取唯一)
* 去重后顺序打乱
* @param arr 数组
*/
public static void findDup4(String[] arr)
{
Set<string> uniques = new HashSet<string>();
Set<string> dups = new HashSet<string>();
for (String a : arr)
{
{
if (!uniques.add(a))
dups.add(a);
}
}
// Destructive set-difference
uniques.removeAll(dups);
System.out.println("Unique words: " + uniques);
System.out.println("Duplicate words: " + dups);
}
/**
* 测试主方法
* @param args 参数
*/
public static void main(String[] args)
{
String[] arr = new String[] {"i", "think", "i", "am", "the", "best"};
findDup1(arr);
findDup2(arr);
findDup3(arr);
findDup4(arr);
}
}