I'd like to count up List's size by element. For example,
List<String> source = Arrays.asList("USA", "USA", "Japan", "China", "China", "USA", "USA");
I'd like to create object (Map) from this source, such as,
int usa_count = result.get("USA").intValue(); // == 4
int javan_count = result.get("Japan").intValue(); // == 1
int china_count = result.get("China").intValue(); // == 2
int uk_count = result.get("UK").intValue(); // == 0 or NPE (both OK)
Now, I composed below.
Map<String, Integer> result = new HashMap<>();
for (String str : source) {
Integer i = result.getOrDefault(str, Integer.valueOf(0));
result.put(str, i + 1);
}
Though, this is enough to my purpose, I think this is not elegant code, and I wanna be a elegant coder. I use Java8. Is there any elegant solution instead of my solution?