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?
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.
One options would be this:
for (T value : set) {
map.put(value, 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With