Array to Map Conversion in Java

Converting an array of strings to a map of strings with the same string as key and value is required in many use cases. Conversion to map enables quick and easy evaluation as to whether a string exists in the list of strings. Conversion to map also enables removal of duplicate strings. The following Java program demonstrates conversion of an array of strings to its corresponding map.

import java.util.HashMap;
import java.util.Map;

/**
 * Converts an array of strings to a map. Each string becomes the key and the corresponding value.
 * Useful for removal of duplicates and quick check on existence of a string in the list.
 * @author jj
 */
public class ArrayToMap {
    
    public static void main(String[] args) {
        String[] colors = new String[]{"blue","green","red"};
        Map<String,String> colorMap = new HashMap<String,String>();
        for(String color:colors) {
            colorMap.put(color, color);
        }
    }
    
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply