Converting a Java Map to a List is a very common task. Map and List are common data structures used in Java. A Map is a collection of key value pairs. While a  List is an ordered collection of objects in which duplicate values can be stored.

In this post, I will discuss different ways to convert a Map to a List.

For the example code in this post, I’ll provide JUnit tests. If you are new to JUnit, I suggest you go through my series on Unit Testing with JUnit.

Converting Map Keys to List

The Map class comes with the keyset() method that returns a Set view of the keys contained in the map. The code to convert all the keys of a Map to a Set is this.

Here is the JUnit test code.

The output on running the test in IntelliJ is this.
Test Output Java Map Key To List

Converting Map Values to List

You use the values() method of Map to convert all the values of Map entries into a List.

Here is the code to convert Map values to a List.

Here is the Junit test code.

The output on running the test in IntelliJ is this.
Test Output Map Values to List

Converting Map to List using Java 8 Streams

If you are into functional programming style, you can use streams introduced in Java 8, along with some utility classes like Collectors, which provides several useful methods to convert stream of Map entries to List.

The stream() method return a stream of the keys from the Set of the map keys that Map.keySet() returns. The collect() method of the Stream class is called to collect the results in a List.

The Collectors.toList() passed to the collect() method is a generalized approach. You can collect elements of Stream in specific collection, such as ArrayList, LinkedList, or any other List implementation. To do so, call the toColection() method, like this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.
Test Output Java Map Keys To List with Java 8 Streams

Converting Map values to List using streams is similar. You only need to get the stream of Map values that map.values() return, like this

The test code is this.

The test output in IntelliJ is this.
Test Output Map Values To List with Stream

Converting Generic Map to List using Stream and Java Lambdas

Till now I showed using method reference with stream to perform conversion of Map to List.
I personally prefer method reference over lambda expressions because I find them clear and concise.
Also, when using collection, you will typically use generic collections and perform conversions between them.

For such collections, you can use streams with lambda expressions, like this.

The code to use method reference is this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.

1
Share

MySQL is the most popular open-source database management system. MySQL uses a relational database and Structured Query Language (SQL) to manage its data.

In this post, I’ll show you how to install MySQL on Ubuntu.

Installing MySQL

There are two ways to install MySQL on Ubuntu. First is to use one of the versions included in the APT package repository by default. Use the following command to find the MySQL version in the APT package repository.

To install MySQL included in the APT repository:

    1. Update the package index on your server

    1. Install the package

During installation, the installer will prompt you to create a root password. Type a secure one and ensure you remember it.

Note: If you are not sure about the version, you can omit the version and run sudo apt-get install mysql-server. This installs the latest version for your Linux distribution.

Installing a Newer MySQL Vwersion

If you want to install the latest MySQL version, such as MySQL 5.7 you’ll need to manually add the MySQL’s repository first. To do so, perform the following steps:

    1. Install the newer APT package repository from the MySQL APT repository page.

    1. Go through the prompt to select and apply the specific MySQL version to install.
    2. Update the package index on your server.

    1. Install the package.

Once installation is complete, MySQL should run automatically. You can check the status of MySQL using the following command.

In order to stop MySQL from the running state, run the following command:

To start MySQL, run the following command:

Refer to the official documentation here for various post-installation setup and configurations of MySQL.

0
Share

When you are developing Spring Boot applications with database interactions, you typically use Hibernate as the Object Relationship Mapping (ORM) tool.

Instead of directly coupling your code with Hibernate, often you’d rather use Spring Data JPA, a Spring Framework project.

Spring Data JPA makes implementation of the data access layer incredibly easy by abstracting most of the complexities involved in persisting data.

Often when you are working with Hibernate and Spring Data JPA, you will need to see what is happening under the hood. It is very helpful to see the actual SQL statements being generated by Hibernate.

Due to the nature of the abstractions offered by Hibernate and Spring Data JPA, its very easy to inadvertently create n+1 queries; which is VERY detrimental to the performance of your application.

In this post, I’ll share a tip on how to configure Hibernate and Spring Data JPA to log executed SQL statements and used bind parameters.

The Application

For the purpose of this post, I’ve created a simple Spring Boot application. In this application, we can perform CRUD operations on a Product entity.

Here is the  Product entity.

Product.java

Below is a JUnit test class to save and retrieve products.

If you are new to JUnit, I’d suggest checking out my JUnit series of posts.

ProductRepositoryTest.java

Activating Logging in Hibernate

To activate the logging of the executed SQL statements with Spring Boot, set the log level of the org.hibernate.SQL category to DEBUG.

If you wish to see the bind values, you can set the log level of org.hibernate.type.descriptor.sql to TRACE .

If you are new to logging frameworks, refer my series on Log4J2.

Here is the logging configuration in the application.properties.

application.properties

Here is the log output showing the SQL statements generated by Hibernate.

Activating Logging with Spring Data JPA

If you are using Spring Data JPA with Hibernate as the persistence provider, add the following two lines in application.properties.

Here is the log output.

Conclusion

As you can see, its very easy to enable the logging of SQL statements with Spring Boot and Hibernate.

Being able to see what Hibernate is actually doing with the database is very important.

Often, when I’m working on a Spring Boot project, I will enable the SQL output just as a sanity check. I may believe everything is okay. But I have, in fact, found problems which I was unaware of by examining the SQL output.

3
Share

A common requirement while programming in Java is to convert String to int. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer’s responsibility to perform any String to int conversions to fulfil business logic, such as calculating discounts, storing age, and so on.

In this post, I’ll discuss how to convert String in Java to int.

The Integer.parseInt Method

The Integer.parseInt() method takes as input a String and returns an int value.

The code to use this method is this.

Here is test code in JUnit.

The output on running the test in InteliJ is this.

Test Output converting string to int in Java

The Integer class also provides an overloaded parseInt() method that additionally accepts the radix (base) to be used while parsing.

Here is the code to use the overloaded method..

Here is the test code.

The output on running the test in InteliJ is this.
Java string to int using radix (base)

Handling Parsing Exception

The parseInt() method throws a NumberFormatException if the String does not contain a parsable int.

Here is sample code to handle the NumberFormatException  gracefully.

This code returns a default int value whenever a NumberFormatException is thrown by the parseInt() method.

Here is the Junit test code.

The test output is this.
Java string to int output

The Integer.valueOf Method

The Integer class also comes with the static valueOf() method to convert String to int. The valueOf() method interprets the String exactly as if it were given to parseInt(). In fact, the valueOf() method internally uses the parseInt() method.

However, valueOf() returns a new Integer object whereas parseInt() returns a primitive int.

The code to parse String using the valueOf() method is this.

Here is the Junit test code.

The test output is this.

Java string to integer output

Note: Similar to parseInt(), the valueOf() method also have an overloaded version that accepts an additional radix value.

Conclusion

Considering Java is a strongly typed language and often interfaces with systems that do not have the type system of Java, converting from a string value to an int value in Java is very common task. As you can see Java provides a number of different ways to convert a string value to an integer value.

 

0
Share