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.


String name;
String language_name;


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) {
            /** case 2: language already added */
            if (languages.containsKey(item.getLanguageName())) {
                        .setNumberItems(languages.get(item.getLanguageName()).getNumberItems() + 1);
            } else {
                /** case 3: language isn't added yet */
                LinkedList<String> languageItems = new LinkedList<String>();
                Language language = new Language(item.getLanguageName(), 1, languageItems);
                languages.put(item.getLanguageName(), language);

Any help would be appreciated!


1 Answer 1

  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.


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.