Is there a way to create a map with keys and values at the same time (I mean a one-line code)? For example, I create a map named map, and I need to use the method "put" whenever I want to add a new pair of key/value. Is there a shorter way to populate a map when we create it?
Map<String, String> map = new HashMap<String, String>();
map.put("A", "32");
map.put("C", "34");
map.put("T", "53");
In Java 9 there are some new Map helper methods defined by JEP 269: Convenience Factory Methods for Collections.
Map<String, String> map = Map.of("A", "32", "C", "34", "T", "53");
But this only works for up to 10 entries. For more than ten, use:
import static java.util.Map.entry;
Map<String, String> map = Map.ofEntries(
entry("A", "32"), entry("C", "34"), entry("T", "53"));
You could write similar helper methods if you needed to do it in earlier versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With