ealeon
ealeon

Reputation: 12460

Java putting set into map

Whats the quickest way to put a set into a map?

public class mySet<T> 
{
    private Map<T, Integer> map;

    public mySet(Set<T> set) 
    {
        Object[] array = set.toArray();

        for(int i =0; i< array.length; i++)
        {
            T v = (T)array[i];
            map.put(v, 1);
        }
    }
}

Right now, I just converted set into an array and loop through the array and putting them in one by one. Is there any better way to do this?

Upvotes: 5

Views: 9543

Answers (2)

Dan D.
Dan D.

Reputation: 32391

One options would be this:

for (T value : set) {
  map.put(value, 1);
}

Upvotes: 9

Sebastian
Sebastian

Reputation: 8025

The quickest way is to not put it into a new Map at all but instead create your own dynamic implementation of the Map interface that dynamically delegates requests to the set instance. Of course this will only work if you need a live view of the Map or the set is immutable. Also depending on the API you require on Map, this might become a lot of work, however AbstractMap will help you a lot here.

Upvotes: 2

Related Questions