What would be the best declaration for the variable below in Java 8?
In Dart:
const Map<Integer,Map<String, String>> data = {
1: {'name': 'John', 'age' : '20'},
2: {'name': 'Mary', 'age' : '30'}
}
CodePudding user response:
Don't model your data as nested Maps, and don't use String where there is a better data type that represent the values allowed in the domain more precisely.
Take advantage of Java's static typing to give yourself as much help as possible as you are writing and modifying your code.
class Person {
private final long id;
private final String name;
private final int age;
public Person(long id, String name, int age) {
... assign to fields ...
}
... getters ...
}
The actual Map
can be:
Map<Long,Person> data = new TreeMap<>();
Which will sort on the natural ordering of the keys.
CodePudding user response:
Note that this map is umodifiable:
Map<Integer, Map<String, String>> data = Map.of(
1, Map.of("name", "John", "age", "20"),
2, Map.of("name", "Mary", "age", "30")
);
If you want to read more about initializing HashMaps you can check this tutorial https://www.baeldung.com/java-initialize-hashmap
CodePudding user response:
If you want to preserve the order, use LinkedHashMap
. Keys are kept in the order they are added. Here are two examples.
- First do it for each entry. Using
computeIfAbsent()
the inner map is computed if not found,otherwise the existing one is used.
Map<Integer, Map<String, String>> data = new LinkedHashMap<>();
data.computeIfAbsent(1, v -> new LinkedHashMap<>()).put("name", "John");
data.computeIfAbsent(1, v -> new LinkedHashMap<>()).put("age", "20");
data.computeIfAbsent(2, v -> new LinkedHashMap<>()).put("name", "Mary");
data.computeIfAbsent(2, v -> new LinkedHashMap<>()).put("age","30");
- Again, using
LinkedHashMap
, pass theMap.of
declarations as an argument to the constructor. The map then becomes mutable.
Map<Integer, Map<String, String>> data =
new LinkedHashMap<>(Map.of(
1,new LinkedHashMap<>(
Map.of("name", "john", "age", "20")),
2, new LinkedHashMap<>(Map.of("name", "Mary",
"age", "30"))));
data.entrySet().forEach(System.out::println);
prints
1={name=john, age=20}
2={name=Mary, age=30}