如何找到一个ArrayList内不同项目的总数。 [英] How to find total number of different items within an arraylist.

查看:209
本文介绍了如何找到一个ArrayList内不同项目的总数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've done some searching but I wasn't able to find a valid solution. I have an arraylist storing Strings such as gum, socks, OJ, dog food...

我有麻烦迭代列表,确定不同的充类型的项目总数。

I am having trouble iterating the list to determine the total number of differnt types of items.

ArrayList<String> Store = new ArrayList<String>();
    this.Store.add("Gum");
    this.Store.add("Gum");
    this.Store.add("Socks");
    this.Store.add("Candy");

该列表中有4项总,但只有三种不同项目(胶,很烂,糖果)。

The list has 4 total items, but only three different kinds of items (Gum, Sucks, Candy).

我将如何设计一个方法来计算3?

How would I design a method to calculate the 3?

推荐答案

Bhesh古隆说,但在code:

int numUnique = new HashSet<String>(Store).size();

如果你确实有什么 StoreItems ,并需要经过的getName()然后我会做

If what you actually have is StoreItems and need to go through getName() then I would do

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

这篇关于如何找到一个ArrayList内不同项目的总数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆