A Map maps keys to values. Map provides following two methods to return keys and values of a map:
| public Collection<V> values() | This method returns a Collection view of the values contained in this map. |
| public Set keySet() | This method returns a Set view of the keys contained in this map |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class MapToListExample {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
map.put("key5", "value5");
//values method returns a collection of values
List<String> values = new ArrayList(map.values());
System.out.println("Values: " + values);
//keySet() method returns a set of keys
Set keys = map.keySet();
System.out.println("keys: " + keys);
}
}
Output
Values: [value1, value2, value5, value3, value4]
keys: [key1, key2, key5, key3, key4]
