How to Convert Map to List in Java?

We can Convert Map to List in java using the Map.keySet and Map.values method. The Map contains the value in the key value pair while on the other hand list contain only value. So keys as a List can be obtained by creating a new ArrayList from a Set returned by the Map.keySet method. while the values as a List can be obtained creating a new ArrayList from a Collection returned by the Map.values method.

Example to convert map to list in java:-

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MaptoList {

	public static void main(String[] args){
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		map.put("byte", 127);
		map.put("short", 32767);
		map.put("int", 2147483647);
		map.put("char", 65535);
		
		System.out.println("convert map to list in java");
		
		List<String> keys = new ArrayList<String>(map.keySet());
		
		for(String key : keys){
			System.out.println("key -> "+key);
		}
		
		List<Integer> values = new ArrayList<Integer>(map.values());
		
		for(Integer value : values){
			System.out.println("values -> "+value);
		}
	}
}

output:-

convert map to list in java 

key -> short
key -> char
key -> byte
key -> int
values -> 32767
values -> 65535
values -> 127
values -> 2147483647

Leave a Comment