Java中HashSet如何进行去重操作呢?
下文讲述java中HashSet进行去重的四种方法分享,如下所示:
LinkedHashSet去重
去重后保持原有顺序(重复数据只保留一条)String[] arr = new String[] {"java", "265", "com", "very", "good", "web"}; Collection<string> noDups = new LinkedHashSet<string>(Arrays.aslist(arr)); System.out.println("(LinkedHashSet) distinct words: " + noDups);
HashSet去重方法一
去重后顺序打乱(重复数据只保留一条)String[] arr = new String[] {"java", "265", "com", "very", "good", "web"}; Collection<string> noDups = new HashSet<string>(Arrays.asList(arr)); System.out.println("(HashSet) distinct words: " + noDups);
HashSet去重方法二
去重后顺序打乱(重复数据只保留一条)String[] arr = new String[] {"java", "265", "com", "very", "good", "web"}; 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);
HashSet去重方法三
去重后顺序打乱(相同的数据一条都不保留,取唯一)String[] arr = new String[] {"java", "265", "com", "very", "good", "web"}; 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);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。