Optimize insertion from ArrayList to HashMap I'm trying to insert data from ArrayList to HashMap&lt;String, Language&gt; optimally.
Many items may have the same languge_name (code below), so I need to group items having the same language in Language class and store languages in a HashMap with the name of the language as a Key.
Item
String name;
String language_name;

Language
String language_name;
int numberItems; 
LinkedList&lt;String&gt; Items;

I solved this as follows:
        ArrayList&lt;Item&gt; items; // given array of items
        HashMap&lt;String, Language&gt; languages = new HashMap&lt;String, Language&gt;();

        items.forEach(item -&gt; {
            /** case 1: language isn't specified */
            if (item.getLanguageName() == null) {
                item.setLanguageName(&quot;unknown&quot;);
            }
            /** case 2: language already added */
            if (languages.containsKey(item.getLanguageName())) {
                languages.get(item.getLanguageName()).getItems().add(item.getName());
                languages.get(item.getLanguageName())
                        .setNumberItems(languages.get(item.getLanguageName()).getNumberItems() + 1);
            } else {
                /** case 3: language isn't added yet */
                LinkedList&lt;String&gt; languageItems = new LinkedList&lt;String&gt;();
                languageItems.add(item.getName());
                Language language = new Language(item.getLanguageName(), 1, languageItems);
                languages.put(item.getLanguageName(), language);
            }
        });

Any help would be appreciated!
The Language class needs the &quot;addItem()&quot; method that combines incrementing numberItems and adding to the Items collection. The design intent here would be to hide the implementation details of adding an item.

The Language class needs a constructor for the first item added.
 Language language = new Language(item);


The languages map should be a specialization class of the HashMap, with its &quot;add(item)&quot; method to hide details of the new/existing item logic.