问题
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