Showing posts with label enum. Show all posts
Showing posts with label enum. Show all posts

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

Tuesday, 7 March 2023

How to get all the enum values in Java?

In this post, I am going to explain how to get all the enum values in Java.

 

Approach 1: Using EnumSet.allOf method.

‘EnumSet.allOf ‘ method return an enum set containing all of the elements in the specified element type.

Set<AppState> appStates = EnumSet.allOf(AppState.class);

Approach 2: Using Class#getEnumConstants method.

Class#getEnumConstants() method return all the elements of this enum class or null if this Class object does not represent an enum type.

AppState[] appStatesArr = AppState.class.getEnumConstants();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Approach 3: Using EnumClass.values() method.

AppState[] appStatesArr = AppState.values();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Find the below working application.

 

EnumValuesDemo.java

 

package com.sample.app;

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

public class EnumValuesDemo {
	private static enum AppState {
		INIT, READY, RUNNING, ABORT;
	}

	public static void main(String[] args) {

		Set<AppState> appStates = EnumSet.allOf(AppState.class);
		System.out.println(appStates + "\n");

		AppState[] appStatesArr = AppState.class.getEnumConstants();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

		appStatesArr = AppState.values();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

	}

}

 

Output

[INIT, READY, RUNNING, ABORT]

INIT
READY
RUNNING
ABORT

INIT
READY
RUNNING
ABORT

 



You may like

Interview Questions

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

Thursday, 24 November 2022

Get the enum constant by name ignoring case

Write a generic method that takes a enum name as input and return an enumeration constant that matches the string without being case sensitive.

 

Signature

public static <T extends Enum<T>> T byNameInsensitiveCase(final Class<T> enumType, final String name)

 

An enum constant in Java is a special type of variable that represents a fixed set of values. Enum constants are declared within an enum type and can be used to define named constants for a specific type or category.

 

Use Cases of Enum Constants:

1.   Representing Predefined Values: Enum constants are often used to define a fixed set of options or states within an application. For example, days of the week, months of the year, colors, etc.

2.   Type Safety: Enums provide type safety, ensuring that only valid values can be assigned to variables of that type.

3.   Switch Statements: Enums are commonly used in switch statements to handle multiple cases elegantly.

4.   Configuration Options: Enums can be used to represent configuration options or settings in applications.

5.   State Machines: Enum constants are useful for defining states in finite state machines, making state transitions clearer and more manageable.

 

Find the below working application.

 


EnumUtils.java

package com.sample.util;

public class EnumUtils {

	/**
	 * 
	 * @param <T>
	 * @param enumClazz - Enum class object
	 * @param name      - name of the enum constant
	 * @return the enum constant that matches to given name. Throws
	 *         {@link IllegalArgumentException} if no enum matches to the given
	 *         name.
	 */
	public static <T extends Enum<T>> T byNameInsensitiveCase(final Class<T> enumClazz, final String name) {
		if (name == null || name.isEmpty()) {
			throw new IllegalArgumentException("name can't be null");
		}

		for (T enumConstant : enumClazz.getEnumConstants()) {
			if (enumConstant.name().compareToIgnoreCase(name) == 0) {
				return enumConstant;
			}
		}
		throw new IllegalArgumentException("No enum constant found for given name : " + name);
	}

}

EnumByNameDemo.java

package com.sample.app;

import com.sample.util.EnumUtils;

public class EnumByNameDemo {

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

		int num;
		String msg;

		Month(int num, String msg) {
			this.num = num;
			this.msg = msg;
		}

		public String toString() {
			return this.name() + " is the " + num + " month and has " + msg;
		}

	}

	public static void main(String[] args) {
		Month month = EnumUtils.byNameInsensitiveCase(Month.class, "auGUst");

		System.out.println(month);

	}

}

Output

AUGUST is the 8 month and has 31 Days




 

Previous                                                 Next                                                 Home

Friday, 11 November 2022

Hibernate 6: handle enum with @Enumerated String attribute

As per 'jakarta.persistence.EnumType', Jakarta support two strategies to handle enum values. Below table summarizes the same.

 

Enum type

Description

ORDINAL

Persist enum according to the enum value’s ordinal position within the enum class, as indicated by java.lang.Enum#ordinal.

STRING

Persist according to the enum value’s name, as indicated by java.lang.Enum#name

 

Example using ORDINAL

@Entity
@Table(name = "person")
public class Person {

	@Id
	private Integer id;

	private String name;

	@Enumerated(EnumType.ORDINAL)
	private Gender gender;

	.........
	.........
}

 

In the ORDINAL example, the gender column is defined as a (nullable) INTEGER type and would hold:

 

a.   NULL: For null values

b.   0: For the MALE enum

c.    1: For the FEMALE enum

 

 

Example using STRING

 

@Entity
@Table(name = "person")
public class Person {

	@Id
	private Integer id;

	private String name;

	@Enumerated(EnumType.STRING)
	private Gender gender;

	..........
	..........
}

 

In the STRING example, the gender column is defined as a (nullable) VARCHAR type and would hold:

 

a.   NULL: For null values

b.   MALE: For the MALE enum

c.    FEMALE: For the FEMALE enum

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘hibernate-enumerated-string-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>hibernate-enumerated-string-demo</artifactId>
    <version>1</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <java.version>15</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.2.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>


    </dependencies>
</project>

Step 3: Create Gender enum.

 

Gender.java

package com.sample.app.enums;

public enum Gender {
    MALE,
    FEMALE
}

Step 4: Create Person entity class.

 

Person.java

package com.sample.app.entity;

import com.sample.app.enums.Gender;

import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "person")
public class Person {

    @Id
    private Integer id;

    private String name;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    public Person(Integer id, String name, Gender gender) {
        this.id = id;
        this.name = name;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

}

Step 5: Create hibernate.cfg.xml file under src/main/resources folder.

 

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>

        <!-- Database Connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://127.0.0.1:5432/test</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>

        <!-- Enable the logging of all the generated SQL statements to the console -->
        <property name="show_sql">true</property>

        <!-- Format the generated SQL statement to make it more readable, -->
        <property name="format_sql">true</property>

        <!-- Hibernate will put comments inside all generated SQL statements to 
            hint what’s the generated SQL trying to do -->
        <property name="use_sql_comments">false</property>

        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <property name="hbm2ddl.auto">update</property>

        <!-- mappings for annotated classes -->
        <mapping class="com.sample.app.entity.Person" />

    </session-factory>

</hibernate-configuration>

Step 6: Define main application class.

 

App.java

package com.sample.app;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.sample.app.entity.Person;
import com.sample.app.enums.Gender;

public class App {
    private static final SessionFactory SESSION_FACTORY = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {

            final StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure("hibernate.cfg.xml").build();

            final Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();

            return metaData.getSessionFactoryBuilder().build();

        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }

    }

    public static void main(final String args[]) {

        Person p1 = new Person(1, "Srinu", Gender.MALE);
        Person p2 = new Person(2, "Swetha", Gender.FEMALE);

        try (final Session session = SESSION_FACTORY.openSession()) {
            session.beginTransaction();

            session.persist(p1);
            session.persist(p2);

            session.getTransaction().commit();

        }

    }
}

Total project structure looks like below.




Run App.java, you will see below messages in the console.

Aug 12, 2022 11:44:32 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.2.Final
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: org.postgresql.Driver
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:postgresql://127.0.0.1:5432/test]
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=postgres}
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 12, 2022 11:44:32 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 12, 2022 11:44:33 AM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Aug 12, 2022 11:44:33 AM org.hibernate.metamodel.internal.EntityInstantiatorPojoStandard resolveConstructor
INFO: HHH000182: No default (no-argument) constructor for class: com.sample.app.entity.Person (class must be instantiated by Interceptor)
Aug 12, 2022 11:44:33 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@43fda8d9] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: 
    
    create table person (
       id integer not null,
        gender varchar(255),
        name varchar(255),
        primary key (id)
    )
Aug 12, 2022 11:44:33 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: 
    insert 
    into
        person
        (gender, name, id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        person
        (gender, name, id) 
    values
        (?, ?, ?)

Query the table person and confirm the same.

test=# SELECT * FROM person;
 id | gender |  name  
----+--------+--------
  1 | MALE   | Srinu
  2 | FEMALE | Swetha
(2 rows)

You can download complete working application from this link.


 

Previous                                                    Next                                                    Home