Master java skills

EnumSet and EnumMap

EnumSet is a class that creates a set from enum types. Let’s understand it from below example

Class declaration

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable 

Example

In the below example, we are creating a set from an enum Fruit.

package com.javatrainingschool;

import java.util.EnumSet;
import java.util.Set;

public class EnumSetExample {

	enum Fruit {APPLE, MANGO, LEECHI, GUAVA, GRAPES};
	
	public static void main(String[] args) {
		
		Set<Fruit> set = EnumSet.of(Fruit.APPLE, Fruit.MANGO);
		
		for(Fruit fruit : set) {
			System.out.println(fruit.toString());
		}
	}
}
Output :
APPLE
MANGO

EnumMap

EnumMap is a map that has its keys of enum types. This class extends Enum and AbstractMap class.

Class Declaration

public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable  

Example

In the below example, we are going to create a map, in which, keys will be an enum type Fruit.

package com.javatrainingschool;

import java.util.EnumMap;
import java.util.Map;
import java.util.Map.Entry;

public class EnumMapExample {
	
	enum Fruit {APPLE, MANGO, LEECHI, GUAVA, GRAPES};

	public static void main(String[] args) {
		
		Map<Fruit, Integer> map = new EnumMap<Fruit, Integer>(Fruit.class);
		map.put(Fruit.MANGO, 4);
		map.put(Fruit.GUAVA, 9);
		map.put(Fruit.LEECHI, 6);
		
		for(Entry<Fruit, Integer> entry : map.entrySet()) {
			System.out.println(entry.getKey() + " : " + entry.getValue());
		}	
	}	
}
Output :
MANGO    : 4
LEECHI    : 6
GUAVA    : 9