Compile Error Problem and Solution while creating immutable map with using Map.of() ?
Hi everyone
In Java, an immutable map is a map that cannot be modified after it has been created.Once an immutable map is created, its contents cannot be changed.
For example;
We want to read csv file and titles of csv rows map with our Java Pojo Object (SalesInfo.class) . We can create immutable map to match both titles of rows and my Java Pojo Object’s props.
@Service
@RequiredArgsConstructor
public class TestService implements ITestService {
private final ResourceLoader resourceLoader;
//key is titles's of row in csv file
//value is properties of SalesInfo object
static Map<String, String> columnMappings = Map.of(
"Customer_ID", "customer",
"Age", "age",
"Gender", "gender",
"Loyalty Member", "loyaltyMember",
"Product Type", "productType"
);
@Override
public List<SalesInfo> readFile(String fileName) throws Exception {
Resource resource = resourceLoader.getResource("classpath:" + "electronic_sales.csv");
HeaderColumnNameTranslateMappingStrategy mappingStrategy =
new HeaderColumnNameTranslateMappingStrategy();
mappingStrategy.setColumnMapping(columnMappings);
mappingStrategy.setType(SalesInfo.class);
CsvToBeanBuilder<SalesInfo> beanBuilder = new CsvToBeanBuilder<>
(new InputStreamReader(resource.getInputStream()));
beanBuilder.withType(SalesInfo.class)
.withSeparator(',')
.withIgnoreLeadingWhiteSpace(true)
.withIgnoreEmptyLine(true)
.withMappingStrategy(mappingStrategy)
.build();
return beanBuilder.build().parse();
}
}
But in future, maybe the number of columns in the document may increase. And we want to add new item to our map.
Map<String, String> columnMappings = Map.of(
"Customer_ID", "customer",
"Age", "age",
"Gender", "gender",
"Loyalty Member", "loyaltyMember",
"Product Type", "productType",
"Rating","rating",
"Order Status","orderStatus",
"Payment Method","paymentMethod",
"Total Price","totalPrice",
"Quantity","quantity",
"Purchase Date","purchaseDate"
);
After that, our code get compile error on creating immutable map code line.
Why?
Because Map.of() method allows you to create a map with up to 10 key-value pairs. If you need more than 10 entries, you would need to use a different approach.
Solution
Using Map.ofEntries() method.
This method can handle any number of key-value pairs.
Map.of() : convenient for creating small maps with a fixed number of entries.
Map.ofEntries(): More suitable when you have a larger number of entries or when the number of entries is not known at compile time.
To use it,see code below
Map<String, String> columnMappings = Map.ofEntries(
Map.entry("Customer ID", "customer"),
Map.entry("Age", "age"),
Map.entry("Gender", "gender"),
Map.entry("Loyalty Member", "loyaltyMember"),
Map.entry("Product Type", "productType"),
Map.entry("SKU", "sku"),
Map.entry("Rating", "rating"),
Map.entry("Order Status", "orderStatus"),
Map.entry("Payment Method", "paymentMethod"),
Map.entry("Total Price", "totalPrice"),
Map.entry("Unit Price","unitPrice"),
Map.entry("Quantity","quantity"),
Map.entry("Purchase Date","purchaseDate"),
Map.entry("Shipping Type","shippingType"),
Map.entry("Add-ons Purchased","addonsPurchased"),
Map.entry("Add-on Total","addonTotal")
);
I hope, it can be useful for you.
Thanx to read.