try

ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
HashMap<String, String> n = new HashMap<String, String>();
n.put("a", "a");
n.put("b", "b");
test.add(n);

HashMap<String, String> m = test.get(0);//it will get the first HashMap Stored in array list 

String strArr[] = new String[m.size()];
int i = 0;
for (HashMap<String, String> hash : test) {
    for (String current : hash.values()) {
        strArr[i] = current;
        i++;
    }
}
Answer from Tarsem Singh on Stack Overflow
🌐
Reddit
reddit.com › r/learnjava › hashmap how to get values from the list value?
r/learnjava on Reddit: HashMap<String, ArrayList> How to get values from the list value?
December 21, 2018 -

Really stumped on this one. I have a HashMap object and the values are a list. I have no idea how to access the individual items in the list values.

Something like this:

public HashMap<String, ArrayList> getData() 
{
    HashMap<String, ArrayList> testData = new HashMap<String, ArrayList>();
    ArrayList<String> stringList = new ArrayList<String>();
    ArrayList<Integer> integerList = new ArrayList<Integer>();
    
    int testInt1 = 8;
    int testInt2 = 12;
    
    String testString1 = "Hello";
    String testString2 = "World";
    
    testData.put("integers", integerList);
    testData.put("strings", stringList);
    
    testData.get("integers").add(testInt1);
    testData.get("integers").add(testInt2);
    testData.get("strings").add(testString1);
    testData.get("strings").add(testString2);
    
    return testData;
}

The HashMap is being returned back to me and I want to access each individual item in each list.

🌐
Team Treehouse
teamtreehouse.com › community › code-challenge-problems-arraylisthashmapstring-string
code challenge problems: ArrayList<HashMap<String, String>> (Example) | Treehouse Community
December 26, 2013 - These HashMap's connect a String to a String like a dictionary. If I were to say KEY_NAME, "one" for instance it would be something like "name" : "one". And the reason you use KEY_NAME and KEY_URL is to tag these data to be able to access it later(You'll understand in a second) After this you create an array of hashmaps (arraylist to be certain but that just means that our array is dynamic so they are not of a fixed length) and call it websites.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › how to store hashmap inside a list
How to Store HashMap Inside a List | Baeldung
April 3, 2025 - @Test public void givenMaps_whenAddToList_thenListContainsMaps() { HashMap<String, List<String>> javaBooksAuthorsMap = new HashMap<>(); HashMap<String, List<String>> phpBooksAuthorsMap = new HashMap<>(); javaBooksAuthorsMap.put("Head First Java", Arrays.asList("Kathy Sierra", "Bert Bates")); javaBooksAuthorsMap.put("Effective Java", Arrays.asList("Joshua Bloch")); javaBooksAuthorsMap.put("OCA Java SE 8", Arrays.asList("Kathy Sierra", "Bert Bates", "Elisabeth Robson")); phpBooksAuthorsMap.put("The Joy of PHP", Arrays.asList("Alan Forbes")); phpBooksAuthorsMap.put("Head First PHP & MySQL", Array
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
Keys and values in a HashMap are actually objects. In the examples above, we used objects of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer.
🌐
Netjstech
netjstech.com › 2015 › 07 › how-to-iterate-hash-map-of-arraylists-java.html
How to Iterate a HashMap of ArrayLists of String in Java | Tech Tutorials
June 27, 2021 - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MapLoop { public static void main(String[] args) { MapLoop mapLoop = new MapLoop(); Map<String, List<String>> cityMap = mapLoop.getMap(); int i = 0; // iterating over a map for(Map.Entry<String, List<String>> listEntry : cityMap.entrySet()){ System.out.println("Iterating list number - " + ++i); // iterating over a list for(String cityName : listEntry.getValue()){ System.out.println("City - " + cityName); } } } /** * A method to create a list and store it in a Map * @return */ private
🌐
Reddit
reddit.com › r/learnjava › how to populate an arraylist in a hashmap?
r/learnjava on Reddit: How to populate an ArrayList in a HashMap?
May 31, 2021 -

I found a thread on stackoverflow, but I'm just not tracking how to do this in my program.

I am reading the book "Job Ready Java" and one of the exercises is to create a program of student quiz scores that stores their name as a String and scores as an ArrayList in a Hashmap. I think what they want is for there to be a Hashmap like this:

StudentNam(key) : Scores(values)

Bob : [47, 59, 60, 27]

Frank : [89, 79, 80, 90]

I completely cannot fathom how to add multiple values into Scores using a HashMap. If it was just a HashMap<String, Integer> then I would do:

Hashmap<String, Integer> students = new HashMap<String, Integer>();
students.put("Bob" 69);

But how to enter an array of values to represent Bob's scores if he has like 10 scores? TYIA and sorry if this is kind of stream of conscious question, but I'm racking my brain on this one.

Top answer
1 of 2
1

Your code is nota completed so I can't know what is test an thearchive. But let's create an example:

HashMap<String, ArrayList<String>> list = new HashMap<String, ArrayList<String>>();
ArrayList<String> anotherlist = new ArrayList<String>();
anotherlist.add("Brazil");
anotherlist.add("USA");
list.put("Augusto", anotherlist);

I hope it helps.

2 of 2
1

Usually your problem is due to re-using the same ArrayList for all people, so that all folks share the same Countries, all held by the one single ArrayList. A solution is to create a new ArrayList for each person -- meaning new ArrayList<String> needs to be inside some loop where you create your traveler's name String.

So for example, you could change your code to this:

ArrayList<String> namelist = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();

// ArrayList<String> archive = new ArrayList<>();

HashMap<String, ArrayList<String>> arkivet = new HashMap<>();

(input.equals("New Country")){
    System.out.println("Name of the Person? ");
    String name = in.nextLine();

    archive = ArrayList<String>(); // **********
    arkivet.put(name, archive);  // ************

    if(namelist.contains(name)){
        System.out.println("Which Country have you visited?");
        String country = in.nextLine();
        if (archive.contains(country)){
            System.out.println("You've already visited this country.");
        }
        else {
            test.add(country);
            thearchive.put(name, country);
            System.out.println("HashMap Contains: " + thearchive);
        }
    }
    else{
        System.out.println("The person does not exist please add first.");
    }
Find elsewhere
🌐
Coderanch
coderanch.com › t › 579785 › java › Iterate-HashMap-type-HashMap-String
How to Iterate HashMap of type HashMap<String, ArrayList<String>> (Java in General forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... HI, I am trying to iterate the hash Map. But, I am getting error at "for loop" please help. I want the each value in the arraylist and do some string manipulation.
Top answer
1 of 5
35

Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

2 of 5
16

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();
Top answer
1 of 1
2

I think what you need is a Map of Map of List.ie.,

Map< String, Map< String, List< String>>>

Sample code below:

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Test {
public static void main(String[] args) throws IOException {

    Map<String,Map<String,List<String>>> scheduleMap=new HashMap<>();

    //Adding
    addSchedule(scheduleMap, "1111", "Engineering", "Tue3");
    addSchedule(scheduleMap, "1111", "Engineering", "Wed2");
    addSchedule(scheduleMap, "1111", "Math", "Wed4");
    addSchedule(scheduleMap, "1111", "Physics", "Fri10");
    addSchedule(scheduleMap, "2222", "Engineering", "Wed2");
    addSchedule(scheduleMap, "2222", "Chemistry ", "Wed4");

    //Printing
    printSchedule(scheduleMap);

}

private static void printSchedule(Map<String, Map<String, List<String>>> scheduleMap) {
    //Sample printing
    for(Entry<String, Map<String, List<String>>> staff : scheduleMap.entrySet()) {
        for(Entry<String,List<String>> subject:staff.getValue().entrySet()) {
            StringBuilder sb=new StringBuilder();
            sb.append(staff.getKey()).append(" : ").append(subject.getKey()).append(" : ");
            for(String sessionTime: subject.getValue()) {
                sb.append(sessionTime).append(", ");
            }
            sb.setLength(sb.length()-2);
            System.out.println(sb.toString());
        }
    }
}

public static void addSchedule(Map<String,Map<String,List<String>>> scheduleMap, String id,String subject,String sessionTime) {
    if(!scheduleMap.containsKey(id)) {
        scheduleMap.put(id, new HashMap<String,List<String>>());
    }
    if(!scheduleMap.get(id).containsKey(subject)) {
        scheduleMap.get(id).put(subject, new ArrayList<String>());
    }
    scheduleMap.get(id).get(subject).add(sessionTime);
}
}
🌐
Blogger
javahungry.blogspot.com › 2021 › 02 › iterate-hashmap-with-arraylist.html
How to Iterate HashMap with ArrayList in Java with Example | Java Hungry
import java.util.*; public class HashMapWithArrayList { public static void main(String args[]) { // Creating HashMap object with ArrayList as Value HashMap<String, ArrayList<String>> map = new HashMap<>(); // Inserting key-value pairs in the above map map.put("USA", new ArrayList(Arrays.as...
🌐
CodingTechRoom
codingtechroom.com › question › store-hashmap-in-list-java
How to Store a HashMap<String, ArrayList<String>> Inside a List in Java? - CodingTechRoom
... // Example snippet showing ... in List HashMap<String, ArrayList<String>> hashMap = new HashMap<>(); ArrayList<String> arrayList1 = new ArrayList<>(Arrays.asList("Value1", "Value2")); ArrayList<String> arrayList2 = new ArrayList<>(Arrays...
🌐
Blogger
javahungry.blogspot.com › 2017 › 10 › difference-between-hashmap-and-arraylist-java-example.html
6 Difference between HashMap and ArrayList in Java with Example | Java Hungry
ArrayList<String> arrlistobj = ...ln("ArrayList object output :"+ arrlistobj); ... (); hashmapobj.put("Alive is ", "awesome"); hashmapobj.put("Love", "yourself"); System.out.println("HashMap object output :"+hashmapobj);...
Top answer
1 of 4
8

Given...

public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();

then something like this should do it.

HashMap<String, String> nhm = new HashMap<>();
for (HashMap xmlFileHm : xmlFileNames ) {
  nhm.putAll(xmlFileHm);
}

but be aware if you have duplicate keys in your hashmaps they will get overwritten.

You should also think about coding to interfaces. Take a look at Map and List rather than typing your collections to implementations (ArrayList and HashMap). Take a look at this thread which is quite interesting What does it mean to "program to an interface"?

Depending on what you are trying to do as well you might consider a MultiMap as this might server your purposes better

Edit After update to the question...

A multimap would be better here with one key and multiple values. Although arguably if the key never changes then you could just store the values in a list. For multiamps you can use Google's guava library or do one yourself. For example (not checked for compilation errors as Im doing this from my head)

Map<String, List<String>> m = new HashMap<>();
if (m.containsKey("key")) {
   m.get("key").add("new value");
}
else {
  List<String> l = new ArrayList<>();
  l.add("new value");
  m.put("key", l);
}
2 of 4
3

You can create a new HashMap, then iterate through the list and put all elements from the map from the list to the main map.

List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
for (Map<String, String> mapFromList : list) {
    map.putAll(mapFromList);
}
Top answer
1 of 2
1

Try this way,hope this will help you to solve your problem.

public class PendingAdapter extends BaseAdapter {

    private List<Map<String, Object>> mPendingItemList;

    public PendingAdapter() {
        mPendingItemList = DataModel.getInstance().getPendingItemList();
    }

    @Override
    public int getCount() {
        return mPendingItemList.size();
    }

    @Override
    public Object getItem(int position) {
        return mPendingItemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (null == convertView) {

            convertView = LayoutInflater.from(getActivity()).inflate(
                    R.layout.pending_item, null);
            holder = new ViewHolder();

            holder.tv_title = (TextView) convertView
                    .findViewById(R.id.pi_tv_title);
            holder.tv_content = (TextView) convertView
                    .findViewById(R.id.pi_tv_content);
            holder.tv_counter = (TextView) convertView
                    .findViewById(R.id.pi_tv_counter);
            holder.tv_ongoing = (TextView) convertView
                    .findViewById(R.id.pi_tv_ongoing);
            holder.tv_type = (TextView) convertView
                    .findViewById(R.id.pi_tv_type);
            holder.tv_date = (TextView) convertView
                    .findViewById(R.id.pi_tv_date);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        @SuppressWarnings("unchecked")
        HashMap<String, String> itemDataHashMap = (HashMap<String, String>) getItem(position);

        holder.tv_title.setText(itemDataHashMap.get("planet"));
        holder.tv_content.setText(itemDataHashMap.get("content"));
        holder.tv_counter.setText(itemDataHashMap.get("counter"));
        holder. tv_type.setText(itemDataHashMap.get("type"));
        holder.tv_ongoing.setText(itemDataHashMap.get("ongoing"));
        holder.tv_date.setText(itemDataHashMap.get("date"));

        convertView.setTag(holder);
        return convertView;
    }

    static class ViewHolder {
        TextView tv_title;
        TextView tv_content;
        TextView tv_counter;
        TextView tv_ongoing;
        TextView tv_type;
        TextView tv_date;
    }
}
2 of 2
1

I would prefer creating a separate model class called News as follows

public class News {
    private String caption;
    private String date;

    // getters and setters for both caption and date
}

Then, instead of using a HashMap, you can directly use ArrayList<News> to save.

To render the fields in getView,

News news = newsUpdateList.get(position);
TextView caption = (TextView) v.findViewById(R.id.newsCaption);
TextView date = (TextView) v.findViewById(R.id.newsDate);

caption.setText(news.getCaption());
date.setText(news.getDate());
🌐
Stack Overflow
stackoverflow.com › questions › 43229126 › compare-hashmapstring-arrayliststring-and-arrayliststring-java
jsp - compare HashMap<String,ArrayList<String>> and ArrayList<String> java - Stack Overflow
HashMap<String,ArrayList<String>> hmm=new HashMap<String,ArrayList<String>>(); for (Entry<String, List<String>> ee : hm.entrySet()) { String key = ee.getKey(); List<String> values = ee.getValue(); List<String> list5=new ArrayList<String>(); ...
🌐
Stanford
web.stanford.edu › class › archive › cs › cs106a › cs106a.1188 › lectures › Lecture20 › Lecture20.pdf pdf
CS 106A, Lecture 20 ArrayLists and HashMaps
Java Ch. 13.2 ... Let’s write a program that reverses a text file. ... To the code! ... Conversion happens automatically! ... Array vs. ArrayList ... Array vs. ArrayList ... Introducing… HashMaps!
🌐
Quora
quora.com › How-do-you-add-an-element-to-an-arraylist-thats-in-a-hashmap
How to add an element to an arraylist that's in a hashmap - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.