HashSet去重

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);
}
}


运行结果:
(LinkedHashSet) distinct words: [i, think, am, the, best]
(HashSet) distinct words: [think, am, best, the, i]
Duplicate detected: i
5 distinct words: [think, am, best, the, i]
Unique words: [think, am, best, the]
Duplicate words: [i]</string></string></string></string></string></string></string></string></string></string>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值