Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java putting set into map

Tags:

java

set

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?

like image 434
ealeon Avatar asked Oct 31 '12 08:10

ealeon


2 Answers

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.

like image 38
Sebastian Avatar answered Sep 19 '22 07:09

Sebastian


One options would be this:

for (T value : set) {
  map.put(value, 1);
}
like image 141
Dan D. Avatar answered Sep 19 '22 07:09

Dan D.