Partner – Microsoft – NPI EA (cat = Baeldung)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Partner – MongoDB – NPI EA (tag=MongoDB)

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

1. Overview

In this quick article, we’ll explore the possibilities to generate a unique Integer from a unique String. While Java offers several ways to achieve this, each approach balances speed, simplicity, and uniqueness differently.

2. What Does Unique Mean?

Uniqueness means a distinct String maps to a distinct int, ideally with no collisions. However, since int has only 2^32 possible values, collisions are possible when hashing very many strings.

Uniqueness isn’t binary – methods like hashCode() offer probabilistic uniqueness with rare collisions, while lookup maps guarantee it.

Each solution should consider how big our input space is and how many collisions in the output may be allowed, if any.

2.1. Validation

To ensure our implementations behave as expected, we test them for uniqueness using a parameterized JUnit test:

private static Stream<Arguments> implementations() {
    return Stream.of(Arguments.of(Named.<Function<String, Integer>> of("toIntByHashCode", StringToUniqueInt::toIntByHashCode)),
      Arguments.of(Named.<Function<String, Integer>> of("toIntByCR32", StringToUniqueInt::toIntByCR32)),
      Arguments.of(Named.<Function<String, Integer>> of("toIntByCharFormula", StringToUniqueInt::toIntByCharFormula)),
      Arguments.of(Named.<Function<String, Integer>> of("toIntByMD5", StringToUniqueInt::toIntByMD5)),
      Arguments.of(Named.<Function<String, Integer>> of("toIntByLookup", StringToUniqueInt::toIntByLookup))
    );
}
@ParameterizedTest
@MethodSource("implementations")
public void given1kElements_whenMappedToInt_thenItShouldHaveNoDuplicates(Function<String, Integer> implementation) {
    Stream<String> strings = uniqueStringsOfSize(1_000); // may be increased for better guarantees

    List<Integer> integers = strings.map(implementation)
      .toList();

    assertThat(integers).doesNotHaveDuplicates();
}

For each implementation we provide, the test generates a large Set of unique Strings and maps each value to an Integer. The assertion checks whether there are any duplicates in the result List, validating the effectiveness of the solution.

3. Solutions

Let’s dive into five practical approaches to generate a unique int from a String.

3.1. Using String.hashCode()

Our first solution is maybe the most obvious one, using hashCode():

public static int toIntByHashCode(String value) {
    return value.hashCode();
}

It’s fast and built into Java, making it ideal for quick caching or non-critical applications. However, String.hashCode() isn’t collision-free, as multiple strings can produce the same int.

We can use this when speed matters more than guaranteed uniqueness.

3.2. Using Chars With Equation

For more control, we can craft a custom formula applied to each character:

public static int toIntByCharFormula(String value) {
    return value.chars()
      .reduce(17, (a, b) -> a * 13 + (b / (a + 1))); // or any other equation
}

It’s simple and customizable but prone to collisions, similar to hashCode(). It’s suitable for educational purposes or when we need a tailored hash function, but we should test thoroughly for collision risks.

3.3. Using CRC32 for Checksums

The third, and robust approach, is the CRC32 checksum from java.util.zip:

public static int toIntByCR32(String value) {
    CRC32 crc32 = new CRC32();
    crc32.update(value.getBytes());
    return (int) crc32.getValue();
}

CRC32 processes the string’s bytes to produce a 32-bit checksum, which is cast to an int. It’s designed for error detection, offering a lower collision probability than hashCode().

While slower, it’s reliable for applications like file indexing or data integrity checks where robustness is key.

3.4. Using MD5 With Byte Shift

For a cryptographic approach, we use MD5 hashing:

public static int toIntByMD5(String value) {
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] hash = digest.digest(value.getBytes());
        return ((hash[0] & 0xFF) << 24) | ((hash[1] & 0xFF) << 16) 
          | ((hash[2] & 0xFF) << 8) | (hash[3] & 0xFF);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 not supported", e);
    }
}

MD5 generates a 128-bit hash, from which we extract the first four bytes to form a 32-bit int using bitwise operations.

It’s slower but has a very low collision risk, making it suitable for high-reliability scenarios like unique key generation. However, it may be overkill for simple use cases.

3.5.  Using Lookup

Our last approach is useful when uniqueness must be guaranteed.

We use a HashMap as a simple persistence layer to store generated integers and their strings:

private static final Map<String, Integer> lookupMap = new HashMap<>();
private static final AtomicInteger counter = new AtomicInteger(Integer.MIN_VALUE);

The implementation in this case is very straightforward – either return an already generated int for a specific String, or increment counter for a new Integer and store it:

public static int toIntByLookup(String value) {
    var found = lookupMap.get(value);
    if (found != null) {
        return found;
    }
    var intValue = counter.incrementAndGet();
    lookupMap.put(value, intValue);
    return intValue;
}

It guarantees uniqueness by using an AtomicInteger counter, ideal for database keys or persistent identifiers. The trade-off is memory usage, which grows with the number of strings.

4. Conclusion

There are multiple approaches for generating a unique int from a String in Java, each with distinct trade-offs.

hashCode() and custom formulas are fast but risk collisions, suitable for caching. CRC32 and MD5 provide robust, low-collision options for reliable indexing. The lookup map ensures uniqueness at the cost of memory, perfect for critical applications. We should choose based on our needs for speed, reliability, or scalability.

As always, the entire code used in this article can be found over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
Subscribe
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments