无重复的可排序 Java 集合

问题描述 投票:0回答:6

我正在寻找可排序(我的意思是在初始化后排序并多次使用比较器)Java 类集合,没有重复项。有没有比编写不透明的代码更纯粹的解决方案,例如防止某些 ArrayList 添加另一个具有与已存在的值相同的值的对象?

编辑1: 我应该添加一些有关排序的解释。我需要使用不同的比较器(实现的多样性)多次对这组值进行排序。

java sorting collections duplicates
6个回答
8
投票

使用套装!常见的实现是HashSetTreeSet。后者在实现 SortedSet 时保留项目的顺序。


6
投票
Set Interface---->SortedSet Interface----->TreeSet Class
Set Interface---->HashSet Class
Set Interface---->LinkedHashSet Class

您可以使用

TreeSet
。它将删除重复项。

TreeSet
实现
SortedSet
接口,以便对输入的元素进行排序

        SortedSet s=new TreeSet();
        s.add(12);
        s.add(12);
        s.add(1);
        s.add(56);
        s.add(6);
        s.add(47);
        s.add(1);
        System.out.println(s);

输出

[1, 6, 12, 47, 56]

1
投票

使用 Set 来获取唯一元素。您始终可以使用 Collections.sort() 对您使用的任何集合进行排序


0
投票

这是一套

用途:

Collection collection = new HashSet();
    

0
投票
最好扩展一个标准集合或从头开始实现一个标准集合。例如:

class SetList<E> extends ArrayList<E> { boolean add(E e) { if (contains(e)) { return false; } else { super.add(e); return true; } } void add(int index, E e) { .. } void addAll(..) {..} void addAll(..) {..} }

然后你就得到了

Collections.sort

,如前所述。不过,我想仔细检查所有内容——我可以想象库方法对 SetList 做出错误的假设,因为它扩展了 ArrayList,从而导致灾难。首先阅读 ArrayList、List 和 Collection 的 javadoc,并真正考虑从头开始。


0
投票
显示找到的每个重复项以及排序后的列表,其中不包含重复的名称 公共类 NameSorter {

public static void main(String[] args) { // Sample array of names ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("David"); names.add("Alice"); // Duplicate entry names.add("Eve"); names.add("Frank"); names.add("Grace"); names.add("Bob"); // Duplicate entry names.add("Hank"); System.out.println("Original List: " + names); // Display each duplicate found and the sorted list without the names that are duplicates }
    
© www.soinside.com 2019 - 2024. All rights reserved.