I would like to count the size of a list by an element. For instance,
List<String> source = Arrays.asList("USA", "USA", "Japan", "China", "China", "USA", "USA");
I would like to create an object (Map) from this source, for example
int usa_count = result.get("USA").intValue();
int javan_count = result.get("Japan").intValue();
int china_count = result.get("China").intValue();
int uk_count = result.get("UK").intValue();
Now I wrote below.
Map<String, Integer> result = new HashMap<>();
for (String str : source) {
Integer i = result.getOrDefault(str, Integer.valueOf(0));
result.put(str, i + 1);
}
Although this is enough for my purpose, I think this is not elegant code, and I want to be an elegant encoder. I am using Java8. Is there an elegant solution instead of my solution?
source
share