`
olive6615
  • 浏览: 5304 次
  • 性别: Icon_minigender_1
  • 来自: 南京
文章分类
社区版块
存档分类
最新评论

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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics