-1

我想知道java中是否有一种方法来计算我的ArrayList中有多少不同的项目而不使用hashset?

如果没有我如何创建一个来计算我的 ArrayList 中有多少不同的项目而不使用哈希集?

谢谢你

4

5 回答 5

5

new HashSet<NestedItem>(theList).size()应该适合您的需要,因为 aSet会自动删除重复的嵌套项。

以一般的方式:

public static <E> int uniqueCount(final List<E> list) {
    return new HashSet<E>(list).size();
}

确保以您需要的方式实现嵌套类型的 equals/hashCode 方法。

于 2013-02-12T18:35:16.433 回答
4

使用一套

集合通常用于包含具有唯一项的集合。你可以这样使用这个属性:

List<String> myArrayList = new ArrayList<>();
Set<String> temporarySet = new HashSet<>();
temporarySet.addAll(myArrayList);
int uniqueCount = temporarySet.size();

使用 Collections.sort()

如果您的所有列表项都实现了 Comparable,您可以预先对列表进行排序,然后计算不等于的连续项。

private static int getUniqueCountUsingSort(List<String> list) {
    if (list.size() < 2) { // obvious case.
        return list.size();
    }

    List<String> listCopy = new ArrayList<>(list);
    Collections.sort(listCopy);
    int uniqueCount = 1;
    for (int i = 1; i < listCopy.size(); i++) { // starts at 1.
                    // Compare with previous item in the sorted list.
        if (!listCopy.get(i).equals(listCopy.get(i-1))) {
            uniqueCount ++;
        }
    }
    return uniqueCount;
}

此方法与 Set 方法具有相同的性能特征,因为 Collections.sort() 是 O(n log(n))。

用手

你也可以简单地用困难的方式来做,但它更慢 O(n^2):

private static int getUniqueCountByHand(List<String> list) {

    int uniqueCount = 0;
    for (int i = 0; i < list.size(); i++) {
        boolean isUnique = true;
        // look if there is another entity before that is equal to this one.
        for (int j = 0; j < i; j++) {
            if (list.get(j).equals(list.get(i))) {
                isUnique = false;
            }
        }
        if (isUnique) {
            uniqueCount ++;
        }
    }

    return uniqueCount;
}
于 2013-02-12T18:34:16.837 回答
3

将列表中的项目添加到 a 中Set并检查其大小。

new HashSet(myListOfItems).size(); // => number of unique elements
于 2013-02-12T18:34:54.797 回答
0

list 是 Object 的 List (ArrayList)。要计算唯一对象:

Set set = new HashSet(list);
int cnt = set.size();

变量 cnt 现在包含唯一元素的数量。

更短:

int cnt = new HashSet(list).size();

套装只包含独特的物品。

于 2013-02-12T18:33:38.183 回答
0

如果您不需要不同的项目,请考虑使用 HashSet。除此之外,如果它还没有包含它,只需扫描并将它们添加到单独的列表中。不过,这大约需要 O(n + n/2) 时间。

于 2013-02-12T18:34:32.963 回答