2
\$\begingroup\$

I'm trying to insert data from ArrayList to HashMap<String, Language> 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<String> Items;

I solved this as follows:

        ArrayList<Item> items; // given array of items
        HashMap<String, Language> languages = new HashMap<String, Language>();

        items.forEach(item -> {
            /** case 1: language isn't specified */
            if (item.getLanguageName() == null) {
                item.setLanguageName("unknown");
            }
            /** 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<String> languageItems = new LinkedList<String>();
                languageItems.add(item.getName());
                Language language = new Language(item.getLanguageName(), 1, languageItems);
                languages.put(item.getLanguageName(), language);
            }
        });

Any help would be appreciated!

\$\endgroup\$
1

1 Answer 1

0
\$\begingroup\$
  1. The Language class needs the "addItem()" 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.

  2. The Language class needs a constructor for the first item added.

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.