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 OverflowReally 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.
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++;
}
}
The uses for an Hashmap should be an Index of HashValues for finding the values much faster. I don't know why you have Key and Values as Strings but if you only need the values you can do it like that:
ArrayList<HashMap<String, String>> test = new ArrayList<>();
String sum = "";
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
sum = sum + current + "<#>";
}
}
String[] arr = sum.split("<#>");
It's not a nice way but the request isn't it too ;)
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.
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.
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.");
}
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.
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>();
ArrayList<Object> parameters = new ArrayList<Object>();
relpace this line with what you want to store in array list like you want to store hash map then create arraylist of type hash map
ArrayList<HashMap<String, String>> parameters = new ArrayList<HashMap<String, String>>();
hope this will help you
Alternative Solution would be using JsonObject and JsonArrays.
they are perfect for such "scenarios" (working with String,Integer and etc with combination of List and Map).
they may also be useful for complex object(e.g. working with Images) but will be abit more difficult to implement. in such cases please refer to java_serialization
in your case use JSONArray instead of your ArrayList and JsonObject instead of HashMap.
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);
}
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);
}
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;
}
}
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());