Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Convert an instance of the legacy type Dictionary to a Map

I'm calling a library that, for API compatibility reasons, returns an instance of type java.util.Dictionary, but I want to have an instance implementing java.util.Map.

How can I easily convert an java.util.Dictionary instance to a java.util.Map instance?

like image 898
oberlies Avatar asked Oct 30 '12 14:10

oberlies


1 Answers

Using Guava and Java 8:

Iterator<String> keysIter = Iterators.forEnumeration(dict.keys());
Map<String, Object> dictCopy = Maps.toMap(keysIter, dict::get);

Alternative in pure Java 8:

List<String> keys = Collections.list(dict.keys());
Map<String, Object> dictCopy = keys.stream()
           .collect(Collectors.toMap(Function.identity(), dict::get)); 
like image 70
Michael Jameson Avatar answered Oct 05 '22 23:10

Michael Jameson