I have some code that splits a String of letters, make a List with that and
later, populate a LinkedHashMap of Character
and Integer
with the letter and its frequency. The code is as following,
List<String> values = Arrays.asList((subjects.split(",")));
for (String value : values) {
char v = value.charAt(0);
map.put(v, map.containsKey(v) ? map.get(v) + 1 : 1);
}
map.put('X', 0);
How can I write it concisely with Java 8 ? Thanks.
To convert all the values of a LinkedHashMap to a List in Java, we can use the values() method. The values() is a method of the LinkedHashMap that returns a Collection of all the values in the map object. We can then convert this collection to a List object.
The LinkedHashMap class is very similar to HashMap in most aspects. However, the linked hash map is based on both hash table and linked list to enhance the functionality of hash map. It maintains a doubly-linked list running through all its entries in addition to an underlying array of default size 16.
Just like HashMap, LinkedHashMap is not thread-safe.
Try this:
LinkedHashMap<Character, Long> counts = Pattern.compile(",")
.splitAsStream(subjects)
.collect(Collectors.groupingBy(
s -> s.charAt(0),
LinkedHashMap::new,
Collectors.counting()));
If you must have an Integer
count, you can wrap the counting collector like this:
Collectors.collectingAndThen(Collectors.counting(), Long::intValue)
Another option (thanks @Holger):
Collectors.summingInt(x -> 1)
As a side note, you could replace your looping update with this:
map.merge(v, 1, Integer::sum);
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