How to find total number of different items within an arraylist.

陌路散爱 提交于 2019-12-08 07:31:15

问题


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.

ie.

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

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

How would I design a method to calculate the 3?


回答1:


What Bhesh Gurung said, but in code:

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

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();



回答2:


Use a Set (HashSet) whose size will give you what you are looking for.




回答3:


This looks like a homework... So, if you do not understand the HashSet solution proposed above (or doning the same with a HashMap), think about doing something like this:

Create a new ArrayList

Take an element and check to see if it exists in the new ArrayList

If it is present in the new ArrayList, do nothing. Else add it.

Do this until you have examined the last element of the ArrayList.

Then, the size of the new array list should be the number you are looking for.




回答4:


You can use the lastIndexOf method and loop through the arraylist.

char count=0;

    for(char i=0; i<araylist.size(); i++){
        if(i == araylist.lastIndexOf(araylist.get(i))){
            count++;
        }
    }

Tested.



来源:https://stackoverflow.com/questions/12085062/how-to-find-total-number-of-different-items-within-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!