Convert the information of prefectures in the DB to a map with a list of names as a value, using category as a key. (I don't know if I write it in Japanese, but in short I want to convert List \ <SampleEntity > to Map \ <String, List \ <String > >)
category | name |
---|---|
Hokkaido | Hokkaido |
Tohoku region | Aomori Prefecture |
Tohoku region | Iwate Prefecture |
Tohoku region | Miyagi Prefecture |
Tohoku region | Akita |
Tohoku region | Yamagata Prefecture |
Tohoku region | Fukushima Prefecture |
Kanto region | Ibaraki Prefecture |
Kanto region | Tochigi Prefecture |
Kanto region | Gunma Prefecture |
Kanto region | Saitama |
Kanto region | Chiba |
Kanto region | Tokyo |
Kanto region | Kanagawa Prefecture |
If you try to do it normally, it is troublesome because you have to branch between the first time (when the list does not exist) and the second and subsequent times (when the list exists) ...
python
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (SampleEntity en : entityList) {
if (!map.containsKey(en.getCategory()) {
map.put(en.getCategory(), new ArrayList<String>());
}
map.get(en.getCategory()).add(en.getName());
}
With LazyMap, you can write this neatly. The declaration is messy, but the logic is simpler.
python
Map<String, List<String>> map = MapUtils.lazyMap(new HashMap<String, List<String>>(),
InstantiateFactory.instantiateFactory(ArrayList.class, null, null));
for (SampleEntity en : entityList) {
map.get(en.getCategory()).add(en.getName());
}
System.out.println(map);
/* ===Output result===
* {Hokkaido=[Hokkaido],
*Tohoku region=[Aomori Prefecture,Iwate Prefecture,Miyagi Prefecture,Akita,Yamagata Prefecture,Fukushima Prefecture],
*Kanto region=[Ibaraki Prefecture,Tochigi Prefecture,Gunma Prefecture,Saitama,Chiba,Tokyo,Kanagawa Prefecture]}
*/
Recommended Posts