Thursday 18 May 2023

Get a map from enum in Java

In this post, I am going to explain how to get a Map from an enum.

private static enum Month {
    JANUARY(1), 
    FEBRUARY(2), 
    MARCH(3), 
    APRIL(4), 
    MAY(5), 
    JUNE(6), 
    JULY(7), 
    AUGUST(8), 
    SEPTEMBER(9), 
    OCTOBER(10),
    NOVEMBER(11), 
    DECEMBER(12);

    private final int index;

    Month(int index) {
        this.index = index;
    }

    public int getIndex() {
        return index;
    }

}

 

As you see above snippet, Month enum defines all the months and their indexes.

Below snippet get a Map from the Month enum, where Month index is the key and Month as a value.

Map<Integer, Month> monthsByIndex = unmodifiableMap(Arrays.stream(Month.values()).collect(Collectors.toMap(Month::getIndex, identity())));

 

Find the below working application.

 

MapFromEnum.java
package com.sample.app.collections;

import static java.util.Collections.unmodifiableMap;
import static java.util.function.Function.identity;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class MapFromEnum {
    private static enum Month {
        JANUARY(1), FEBRUARY(2), MARCH(3), APRIL(4), MAY(5), JUNE(6), JULY(7), AUGUST(8), SEPTEMBER(9), OCTOBER(10),
        NOVEMBER(11), DECEMBER(12);

        private final int index;

        Month(int index) {
            this.index = index;
        }

        public int getIndex() {
            return index;
        }

    }

    public static void main(String[] args) {
        Map<Integer, Month> monthsByIndex = unmodifiableMap(
                Arrays.stream(Month.values()).collect(Collectors.toMap(Month::getIndex, identity())));

        for (Entry<Integer, Month> entry : monthsByIndex.entrySet()) {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }
    }
}

 


Output

1   JANUARY
2   FEBRUARY
3   MARCH
4   APRIL
5   MAY
6   JUNE
7   JULY
8   AUGUST
9   SEPTEMBER
10  OCTOBER
11  NOVEMBER
12  DECEMBER

 

 

 


You may like

Interview Questions

Collection programs in Java

Array programs in Java

Get the stream from an iterator in Java

Get the stream from Enumeration in Java

LinkedHashTable implementation in Java

Get the enumeration from a Collection

Get the enumeration from an Iterator in Java

No comments:

Post a Comment