The createMappingKey() method creates a line only once. Hashcode, which is used for Maps, is evaluated only once for String, since it is immutable. But the method creates some StringBuilders to perform concatenation. The string representation itself is only created for the subsequent presentation of the hash code in HashMap. So this is a waste product without any value.
You can make it useful and use other purposes. Your MyKey class may also be immutable, so you can pre-compute your own hash code and cache it. This can improve performance when the HashMap can be accessed or changed very often because calls to equals () / hashCode () are faster.
A very proprietary key class sounds like the objectโs best orientation, but of course introduces additional source code and clutter. But this probably better says what the key really is: is it just a string concatenation? I doubt it. It can be an identifier for a client or something like that, so why not call it that?
public class CustomerIdentifier { public CustomerIdentifier(String tenantId, String customerName, String location) {
This approach allows you to determine in your project how the Customer object is identified. It encapsulates key generation - you are not dependent on whether to use it : as a delimiter or something else. Other clients (for example, if accessing the HashMap with other code is not under your control) may be easier because they simply use the CustomerIdentifier instead of duplicating the key generation code (this is a bit, but the problem can often arise later when someone changes the delimiter, but another code is not ...)
In addition, this approach allows you to put a check on x / y / z values โโin a class. Can they be empty? Can they be colons? How do you distinguish them?
x=':' y='' z='' is :::: x='' y=':' z='' is :::: x='' y='' z=':' is ::::
The disadvantage is that it is probably harder to debug. In such cases, you would like to implement toString () in this class, so that you can more quickly look at the hashmap in the debugger view and find the key you are looking for.
The second drawback is that you often have to create new key objects for code that accesses the HashMap but only has x / y / z values.