Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write using the Java 8 to populate the LinkedHashMap?

Tags:

java

java-8

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.

like image 635
Heisenberg Avatar asked Feb 09 '17 00:02

Heisenberg


People also ask

How do I create a LinkedHashMap list in Java?

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.

Which data structure is used in LinkedHashMap?

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.

Is a Java LinkedHashMap thread safe?

Just like HashMap, LinkedHashMap is not thread-safe.


1 Answers

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);
like image 68
shmosel Avatar answered Oct 13 '22 17:10

shmosel