Eldar Nezametdinov
Eldar Nezametdinov

Reputation: 1925

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

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

Upvotes: 0

Views: 4417

Answers (5)

assylias
assylias

Reputation: 328598

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

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

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

Upvotes: 1

JHS
JHS

Reputation: 7871

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

Upvotes: 1

bas
bas

Reputation: 1678

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.

Upvotes: 6

Adam Siemion
Adam Siemion

Reputation: 16039

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

Upvotes: 2

Related Questions