Inside the arraylist i need to add hashmap values and i declared
arralist as
public static ArrayList<Map<String, Object>> UploadingArray = new ArrayList<>();
and map
Map<String,Object> image_details=new HashMap<>();
and
int imageid;
for(int i=0;i<4;i++){
imageid=i;
new method()
}
image id will change when this function calling from another activity
imageid=(another activity).imageid;
new method(){
image_details.put("imageid",i);
image_details.put("status","New");
UploadingArray.add(imageid,image_details);
}
but the result of UploadingArray like
[0]
id=3;
status=New
[1]
id=3;
status=New
[2]
id=3;
status=New
[3]
id=3;
status=New
why the id is same for all position? any one know the issue please help me?
This is just a model the "i" value will be changed by calling method
They have the same values because you're adding the same object multiple times to your ArrayList.
You should create a new Map object inside your loop:
ArrayList<Map<String, Object>> list = new ArrayList<>();
for(int i = 0; i < 4; i++){
// creating new object on every iteration
Map<String, Object> imageDetails = new HashMap<>();
imageDetails.put("imageId", i);
imageDetails.put("status", "new");
list.add(imageId, imageDetails);
}
Related
I have a list of custom object,
public class Assignmentsdata {
String assignmentId;
String teacherId;
String groupName;
String sectionId;
String levelId;
String startTime;
}
ArrayList<Assignmentsdata> list = new ArrayList<>();
lets say there are 20 elements in that list.
Now I want to get the output which is a hashmap of startTime as a key and the Value would be a new HashMap of GroupID and a list of Assignments of those that had the same groupName.
OutPut Example
HashMap<startTime,HasMap<groupName,List> hashMap = new HashMap();
a little more insight about the problem: First I want to categorise based on startTime(Month) then i want to categorise based on groupName, Thanks in advance.
I have successfully categorised based on group name and created a map through below code:
for( int i = 0; i<assignmentsdataArrayList.size();i++ ){
if (hashMap.size()>0){
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}else {
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}
After that I am lost on how to categorise this hashmap based on the startDate and create a hashmap that would look like the above hashmap in the output heading.
your code may throw a NullPointerException at the first if branch
if (hashMap.size()>0)
{hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
the map.size()>0 doesnt means the Value of GroupName has put a new ArrayList already.
the anwser of using loop should like this
Map<String, Map<String, List<Assignmentsdata>>> map = new HashMap<>();
for (Assignmentsdata assignmentsdata : list) {
if (!map.containsKey(assignmentsdata.getStartTime())) {
map.put(assignmentsdata.getStartTime(), new HashMap<>());
}
Map<String, List<Assignmentsdata>> startTimeMap = map.get(assignmentsdata.startTime);
if (!startTimeMap.containsKey(assignmentsdata.getGroupName())) {
startTimeMap.put(assignmentsdata.getGroupName(), new ArrayList<>());
}
startTimeMap.get(assignmentsdata.groupName).add(assignmentsdata);
}
or you could use the java stream().collect(Collectors.groupingBy()) api to get the result easily
Map<String, Map<String, List<Assignmentsdata>>> result = list.stream()
.collect(Collectors.groupingBy(Assignmentsdata::getStartTime,Collectors.groupingBy(Assignmentsdata::getGroupName)));
I am answering my own question as I solved it if anyone has a better answer please passed your answer aswell, ill accept another answer suitable and efficient answer.
for( int i = 0; i<assignmentsdataArrayList.size();i++ ){
if (hashMap.size()>0){
if (hashMap.get(assignmentsdataArrayList.get(i).getGroupName())==null){
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}else{
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}else {
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}
// above part is already in the question. the second part i looped through the hashMap then the list once again, and checking if list and map entry have same group name, then made the startdate key that indexed element from the list.
HashMap<String, Map.Entry<String, ArrayList<Assignmentsdata>>> hashMapHashMap = new HashMap<>();
for (var entry : hashMap.entrySet()){
for( int j = 0; j<assignmentsdataArrayList.size();j++ ){
if (assignmentsdataArrayList.get(j).getGroupName()==entry.getKey()){
hashMapHashMap.put(assignmentsdataArrayList.get(j).getStartTime(),entry);
}
}
hashMapHashMap.put(entry.getValue().get())
}
I have a problem that I am unable to understand..
I am building a HashMap called wholeSetHistory.
I am building a HashMap with the same keys and values that wholeSetHistory has, called wholeSetHistoryT.
In a similar way I create two HashMaps called wholeSetRates, wholeSetRatesT
All HashMaps have this format HashMap<String, HashMap<String, Double>> .
I have this function that creates a train set
public void createTrainSet(HashMap<String, HashMap<String, Double>> wholeSetRates, HashMap<String, HashMap<String, Double>> wholeSetHistory){
for(String fbid : wholeSetHistory.keySet()){
ArrayList<String> locsBe = new ArrayList<>();
HashMap<String, Double> locss = wholeSetHistory.get(fbid);
HashMap<String, Double> locss2 = wholeSetRates.get(fbid);
for(String loc : locss.keySet()){
if(locss.get(loc)==1.0){
locsBe.add(loc);
}
}
ArrayList<Integer> randomNums = new ArrayList<>();
for(int i=0; i<2; i++){
Random rn = new Random();
int randomNum;
do{
int range = locsBe.size() - 1 + 1;
randomNum = rn.nextInt(range);
}while(randomNums.contains(randomNum));
randomNums.add(randomNum);
locss.put(locsBe.get(randomNum), 0.0);
locss2.put(locsBe.get(randomNum), 0.0);
wholeSetHistory.put(fbid, locss);
wholeSetRates.put(fbid, locss2);
}
randomNums.clear();
}
}
So, later on I am using it like this
(... creation of wholeSetHistory, wholeSetHistoryT, wholeSetRates, wholeSetRatesT)
System.out.println(wholeSetHistory.get("1"));//1
createTrainSet(wholeSetRatings, wholeSetHistory, nearUserIDWithVisitedTrueValues);
That means that I am passing to the function as paramater only wholeSetHistory
Although, later I
System.out.println(wholeSetHistory.get("1"));//2
System.out.println(wholeSetHistoryT.get("1"));//3
This is what happens:
The values that changes in wholeSetHistory changes in wholeSetHistoryT too!
For example, prints 2 and 3 are the same(!) and different from 1.
Any help is mych appreciated.
A reference points to a location in memory. If you add the same reference to two different data structures, altering the reference in one will also alter the other. They point to the same object in memory.
I can't to take value from dataF when I use map.put that say error.if I replace map.put("Nos",dataF); to map.put("Nos",dataF[arrLength]) It's work but It's return [Ljava.lang.string;#b1f37df0
ArrayList<HashMap<String,String[]>> ArrList = new ArrayList<HashMap<String,String[]>>();
Intent intent = getIntent();
String[] dataF = intent.getStringArrayExtra("Money");
ListView list1 = (ListView)findViewById(R.id.listView1);
int arrLength = dataF.length;
for(int i=0;i<arrLength;i++)
{
HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("Nos", dataF[arrLength]); // << error
ArrList.add(map); // << error
}
ListAdapter adapters = new SimpleAdapter(resultActivity.this,ArrList,
R.layout.activity_column,
new String[] {"Nos"},new int[] { R.id.textView1});
list1.setAdapter(adapters);
you try put map.put("Nos", dataF[arrLength]); as HashMap<String, String[]> but dataF[arrLength] is a one String and your hashmap need one Array of String.
you can change that to:
map.put("Nos", dataF);
if you solve this i think next line is solved too.
and with dataF[arrLength] you must get ArrayIndexOutOfBounds because last index of your array is dataF[arrLength - 1]
UPDATE
with your say on comment i think you try show hashMpa.getValue(); but your value is array of String so you need show one index of that like hashMpa.getValue()[0];
you need following for showing values:
String[] value = hashMap.getValue();
for ( int i = 0 ; i < value.lenght() ; i++)
Log.d("index "+i , value[i]);
Update the code as below::
HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("Nos", dataF); // Pass the Array instead String
ArrList.add(map);
For an Android application that I'm building for my internship, I'm trying to display a list
of tickets from the current logged in user and display them in a ListView. Let me paste some of my code to let you see where I'm at currently:
JSONArray finalResult = finalResultObject.getJSONArray(TAG_TICKETS);
System.out.println("this is finalResult: " + finalResult);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
for (int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
if (c.has(TAG_CLIENT_NAME) && !c.isNull(TAG_CLIENT_NAME)) {
String clientName = c.getString(TAG_CLIENT_NAME);
map.put("client_name_map", clientName);
// System.out.println(clientName);
}
if (c.has(TAG_PROJECT_NAME) && !c.isNull(TAG_PROJECT_NAME)) {
String projectName = c.getString(TAG_PROJECT_NAME);
map.put("project_name_map", projectName);
}
// adding HashList to ArrayList
ticketList.add(map);
// System.out.println(map);
}
ListAdapter adapter = new SimpleAdapter(SecondActivity.this, ticketList, R.layout.list_item, new String[] { "client_name_map", "project_name_map" }, new int[] { R.id.client_name,
R.id.project_name });
eventualListAdapter = adapter;
I've got a couple of prints in between, left them in there to let you guys see what I'm looking at right now. My problem is that I do get the required number of items, but it repeats the same item (so it does loop through the array, but doesn't update the values). I'm currently completely new to Android, and therefore still figuring out which kind of Adapters to use etc.
In the end I'm passing the adapter to eventualListAdapter, which I created within the main thread, so I can easily call it to update the UI (I'm not sure if this is anywhere near a clean way, just trying to get things working at this point)
Thanks in advance,
Dennis
You are using the same HashMap instance for all Itens. Just move the HashMap creation to inside the loop:
// adding each child node to HashMap key => value
for (int i = 0; i < finalResult.length(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = finalResult.getJSONObject(i);
if(c.has(TAG_CLIENT_NAME)&&!c.isNull(TAG_CLIENT_NAME)){
String clientName = c.getString(TAG_CLIENT_NAME);
map.put("client_name_map", clientName);
//System.out.println(clientName);
}
if(c.has(TAG_PROJECT_NAME)&&!c.isNull(TAG_PROJECT_NAME)){
String projectName = c.getString(TAG_PROJECT_NAME);
map.put("project_name_map", projectName);
}
// adding HashList to ArrayList
ticketList.add(map);
//System.out.println(map);
}
I am trying to add hashmaps to array list.
But the map(completeEntrie) is overriding the previous values when I am trying to add more than one value to arraylist(listOfCompleteEntries)
public class MapExample {
public static void main(String a[]) {
ArrayList listOfCompleteEntries = new ArrayList();
Map<String, String> completeEntrie = new HashMap<String, String>();
for (int i = 0; i < 3; i++) {
completeEntrie.put("KEY_NAME", "Number:" + i);
System.out.print(completeEntrie.toString());
listOfCompleteEntries.add(completeEntrie);
System.out.println(listOfCompleteEntries.toString());
}
System.out.println(listOfCompleteEntries.toString());
}
}
Output for the above code is
{KEY_NAME=Number:0}[{KEY_NAME=Number:0}]
{KEY_NAME=Number:1}[{KEY_NAME=Number:1}, {KEY_NAME=Number:1}]
{KEY_NAME=Number:2}[{KEY_NAME=Number:2}, {KEY_NAME=Number:2}, {KEY_NAME=Number:2}]
[{KEY_NAME=Number:2}, {KEY_NAME=Number:2}, {KEY_NAME=Number:2}]
But i want the output to be like this
{KEY_NAME=Number:0}[{KEY_NAME=Number:0}]
{KEY_NAME=Number:1}[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}]
{KEY_NAME=Number:2}[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}, {KEY_NAME=Number:2}]
[{KEY_NAME=Number:0}, {KEY_NAME=Number:1}, {KEY_NAME=Number:2}]
Also please explain why is this map overriding the previous map in arraylist.
Thanks for your help.
Despite the irrelevant title, you need to construct a new map instance for each unique entry you want to add to the array list. Without this, you are modifying the same map instance.