如何查找arraylist中不同项目的总数.

Rya*_*ers 1 java loops arraylist duplicates

我做了一些搜索,但我找不到有效的解决方案.我有一个arylylist存储字符串,如口香糖,袜子,OJ,狗粮......

我无法迭代列表以确定不同类型项目的总数.

即.

ArrayList<String> Store = new ArrayList<String>();
    this.Store.add("Gum");
    this.Store.add("Gum");
    this.Store.add("Socks");
    this.Store.add("Candy");
Run Code Online (Sandbox Code Playgroud)

该列表共有4个项目,但只有三种不同的项目(Gum,Sucks,Candy).

我如何设计一种计算3的方法?

aio*_*obe 10

Bhesh Gurung说的是什么,但在代码中:

int numUnique = new HashSet<String>(Store).size();
Run Code Online (Sandbox Code Playgroud)

如果您实际拥有的是StoreItems并且需要经历getName()那么我会这样做

Set<String> itemNames = new HashSet<String>();
for (StoreItem item : Store)
    itemNames.add(item.getName());
int numUnique = itemNames.size();
Run Code Online (Sandbox Code Playgroud)


Bhe*_*ung 5

使用Set(HashSet)大小将为您提供所需的内容.