How do I format a number as percentage with fraction digits?

In Java, the `NumberFormat` class of `java.text` package can be used to format numbers. For formatting a number as a percentage string with fraction digits, you can use the `getPercentInstance()` method that returns a percentage format for the current default `Locale`.

Here is a sample code snippet showing how to format a number as a percentage string with two digits of fractions:

``````package org.kodejava.text;

import java.text.NumberFormat;

public class FormatPercentage {
public static void main(String[] args) {
double number = 0.12345;

// Get an instance of NumberFormat for percentage
NumberFormat percentFormat = NumberFormat.getPercentInstance();

// Set the fraction digits - change this value to control the
// number of fraction digits.
percentFormat.setMinimumFractionDigits(2); // set the minimum
percentFormat.setMaximumFractionDigits(4); // set the maximum

// Format the number as a percentage
String formattedPercent = percentFormat.format(number);

System.out.println("Number as percentage: " + formattedPercent);
}
}
``````

Output:

``````Number as percentage: 12.345%
``````

In the above example, `0.12345` will be formatted as `12.35%` because we have set the `MinimumFractionDigits` to `2` which means up to two decimal points will be included in the formatted percentage. If we also set the `MaximumFractionDigits` it will allow us to have up to four decimal points in the output value, here we have `12.345%`.

Note that the actual percentage is calculated by multiplying the number by `100`, so `0.12345` becomes `12.345%` and then rounded to `12.35%` (because of the fraction digits setting, in this case we only set the minimum fraction digits to two decimal points).

We can also use the `DecimalFormat` class. The `DecimalFormat` class in Java is used to format decimal numbers. It is a subclass of `NumberFormat` and you can customize the format of your number using it.

Here’s a simple example of how you can format a number as a percentage string using `DecimalFormat`:

``````package org.kodejava.text;

import java.text.DecimalFormat;

public class DecimalFormatPercentDemo {
public static void main(String[] args) {
double number = 0.123;

// Create a new DecimalFormat instance with a percentage pattern
DecimalFormat df = new DecimalFormat("#%");

// Set the number of fraction digits
df.setMinimumFractionDigits(2);

// Format the number into a percentage
String percentage = df.format(number);

System.out.println(percentage);
}
}
``````

This program will output 12.30%

The `"#%"` pattern means that the number should be formatted as a percentage. And `df.setMinimumFractionDigits(2)`; means that the decimal will be formatted to two places.

The `DecimalFormat` will automatically multiply our value by 100, which is why 0.123 appears as 12.30%.

How do I create a table in PDF document using iText 8?

When it comes to generating PDF documents dynamically, iText 8 is a powerful and versatile Java library that provides a wide range of functionalities. One common requirement in PDF generation is the need to include tables to present structured data. In this blog post, we will explore how to create a table in a PDF document using the iText 8 library.

The `Table` class in iText 8 is a layout element that represents data in a two-dimensional grid. It allows you to create tables with rows and columns to organize and display data in a structured format.

To create a table using iText 8, we would first need to create an instance of `Document` class where the table will be added. We then define a `Table` object either by passing the number columns, or an array of `float` for the column width as parameter.

Here is how you can create a table with iText 8:

``````package org.kodejava.itext;

import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.properties.TextAlignment;

import java.io.FileNotFoundException;

public class CreateTable {
public static void main(String[] args) throws FileNotFoundException {
String destination = "table_example.pdf";
PdfWriter writer = new PdfWriter(destination);

PdfDocument pdf = new PdfDocument(writer);
try (Document document = new Document(pdf)) {

float[] pointColumnWidths = {150F, 200F, 100F};
Table table = new Table(pointColumnWidths);

.setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
.setBackgroundColor(DeviceGray.GRAY));
.setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
.setBackgroundColor(DeviceGray.GRAY));
.setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
.setBackgroundColor(DeviceGray.GRAY));

// Add cells to the table

}
}
}
``````

This will create a new document with a table including three columns and three rows. The first row is the table header, we style it with a gray background, set the font weight to bold and center aligned the text.

Maven Dependencies

``````<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>8.0.2</version>
<type>pom</type>
</dependency>
``````

How do I use ConcurrentHasMap forEach() method?

The `forEach()` method in `ConcurrentHashMap` is used for iteration over the entries in the map. The method takes a `BiConsumer` as an argument, which is a functional interface that represents an operation that accepts two input arguments and returns no result.

Here’s an example of how to use `forEach()` with a `ConcurrentHashMap`:

``````package org.kodejava.util.concurrent;

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapForEachExample {
public static void main(String[] args) {
// Create a new ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);

// Use forEach to iterate over the ConcurrentHashMap.
// The BiConsumer takes a key (k) and value (v), and we're
// just printing them here.
map.forEach((k, v) -> System.out.println("Key: " + k + ", Value: " + v));
}
}
``````

Output:

``````Key: One, Value: 1
Key: Four, Value: 4
Key: Two, Value: 2
Key: Three, Value: 3
``````

In the above example, `forEach()` is used to iterate over the entries of the `map`. For each entry, the `key` and `value` are printed. The `forEach()` method is often more convenient to use than an iterator, especially when you’re only performing a single operation (like print) for each entry in the map.

What is ConcurrentHasMap and how do I use it in Java?

`ConcurrentHashMap` is a class in Java that implements the `ConcurrentMap` interface. It is part of the Java Collection Framework and extends the `AbstractMap` class.

`ConcurrentHashMap` is thread-safe, which means it is designed to support high concurrency levels by handling multiple threads concurrently without any inconsistencies. It allows multiple threads to perform `retrieve` (`get`) and `update` (`insert` & `delete`) operations. Internally, `ConcurrentHashMap` uses concepts of Segmentation to store data which allows higher degree of concurrency.

Here is an example of how to use `ConcurrentHashMap` in Java:

``````package org.kodejava.util;

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
public static void main(String[] args) {
// Create a ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);

// Retrieve elements
Integer one = map.get("One");
System.out.println("Retrieved value for 'One': " + one);

// Remove an element
map.remove("Two");

// Print all elements
map.forEach((key, value) -> System.out.println(key + " = " + value));
}
}
``````

Output:

``````Retrieved value for 'One': 1
One = 1
Three = 3
``````

In this example, we’re creating a `ConcurrentHashMap`, adding some elements to it, retrieving an element, removing an element, and finally printing all the elements.

One thing to note is that while `ConcurrentHashMap` allows multiple threads to read and write concurrently, a `get()` operation might not reflect the latest `put()` operation, since it might be looking at a previous segment. Further thread synchronization mechanisms might be necessary depending on your exact use case.

Also, worth mentioning, `null` values and `null` keys are not permitted in `ConcurrentHashMap` to prevent ambiguities and potential errors in multithreaded contexts. If you try to use `null`, `ConcurrentHashMap` will throw a `NullPointerException`.

Here’s an example demonstrating the usage of `ConcurrentHashMap` in a multithreaded context:

``````package org.kodejava.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

try (ExecutorService executor = Executors.newFixedThreadPool(5)) {

// Runnable task to increment a value in the map
Runnable task = () -> {
for (int i = 0; i < 10; i++) {
map.compute("TestKey", (key, value) -> {
if (value == null) {
return 1;
} else {
return value + 1;
}
});
}
};

for (int i = 0; i < 5; i++) {
}

// Shut down the executor and wait for tasks to complete
executor.shutdown();
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
}

System.out.println("Final value for 'TestKey': " + map.get("TestKey"));
}
}
``````

Output:

``````Final value for 'TestKey': 50
``````

In this example, we’re creating a `ConcurrentHashMap` and a thread pool with `ExecutorService`. We’re then defining a `Runnable` task, which increments the value of the “TestKey” key in the map 10 times.

The task uses `ConcurrentHashMap`‘s `compute()` method, which is atomic, meaning that the retrieval and update of the value is done as a single operation that cannot be interleaved with other operations. We then submit the task to each of the five threads in our thread pool. After all threads have completed their tasks, we retrieve and print the final value of “TestKey”.

If everything works correctly, the output should be “Final value for ‘TestKey’: 50”, because we have 5 threads each incrementing the value 10 times. This demonstrates the thread-safety of `ConcurrentHashMap`, as the `compute()` operation is done atomically and many threads were able to modify the map simultaneously without causing inconsistencies. If we were using a plain `HashMap` instead, we could not guarantee this would be the case.

Impact on using Spring Data native query @Query to Persistence Context?

Using Spring Data’s `@Query` annotation with native SQL queries can have several impacts on Hibernate or JPA persistence context:

Bypassing JPQL Translation: When you use a native SQL query with `@Query`, you bypass JPQL (Java Persistence Query Language) translation. This means that the query is written in the native SQL dialect of the underlying database, rather than in JPQL, which is database agnostic. While this can provide more flexibility in complex queries or when leveraging database-specific features, it also ties your application more tightly to the underlying database, potentially reducing portability.

Direct Interaction with Database: Native queries bypass the entity manager’s persistence context, as they don’t involve managed entities directly. This means that Hibernate or JPA typically not manage the entities returned by a native query. As a result, changes to these entities won’t be automatically synchronized with the database unless you manually manage them using entity manager operations.

Performance Considerations: Native queries might offer performance benefits in certain cases, especially when dealing with complex queries or when JPQL is not sufficient to express the logic efficiently. However, they also come with potential drawbacks such as decreased portability and increased maintenance complexity.

Mapping to Entities: While native queries return results in the form of arrays or lists of objects, you can still map these results to entities manually if needed. However, this requires additional code for mapping the columns returned by the native query to the fields of your entity classes.

Security Risks: Using native queries opens up potential security risks such as SQL injection if the queries involve user input. You need to be careful to properly sanitize and validate any user-provided parameters before incorporating them into native queries to prevent such vulnerabilities.

Testing and Maintenance: Native queries can make your code harder to test and maintain, especially when compared to JPQL queries. Since JPQL queries are language agnostic and are validated by JPA providers during application startup, they offer better compile-time safety and easier refactoring.

In summary, while native queries can be powerful and useful in certain scenarios, they should be used judiciously, considering the trade-offs in terms of performance, portability, security, and maintenance complexity. It’s often preferable to use JPQL queries where possible and resort to native queries only when necessary for performance optimization or when dealing with database-specific features.