How to count unique elements in the array? Need only idea

我怕爱的太早我们不能终老 提交于 2020-01-07 05:48:09

问题


For example: String[] str = {"M1","M1","M1","M2","M3"};
The most recommended is the answer - HashSet. Which methods or you have better idea?


回答1:


Unless you want to implement this yourself, a Set is the way to go. A set will only allow unique elements to be added and will automatically filter duplicates.

The HashSet functionality works as follows:

The hash is computed for the object. Next the set checks if any of the objects with the same hash-value .equals() the new value. If so, the new value is ignored. If not, it is added to the set.

If you add everything to the set and then ask for its size, you will get the amount of unique elements.




回答2:


new HashSet(Arrays.asList(str)).size();



回答3:


I prefer to use things that are already provided natively. Which in your requirement is Set.

You can do the following -

Set<String> set = new HashSet<String>(Arrays.asList(str));
set.size();



回答4:


You can try this too

    String[] str = {"M1","M1","M1","M2","M3"};
    HashMap<String,String> map=new HashMap<>();
    for(String i:str){
        map.put(i, i);
    }
    System.out.println(map.keySet().size());



回答5:


Instead of creating a temporary list as in other answers, you can also use:

Set<String> set = new HashSet<> ();
Collections.addAll(set, str);
int countUnique = set.size();


来源:https://stackoverflow.com/questions/18060229/how-to-count-unique-elements-in-the-array-need-only-idea

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