I have a database call that will return a result set with city and states into a result set object called cityAndState. I am trying to loop through and put each city and state into a map and then add to an array list of maps.
So I have an array list with 50 city and state Maps with <key,values> of city and state. For instance [{city-Los Angeles, state=California},...] But each time I am overwriting the value.
Map<String,String> citiesAndStateCombinations = new HashMap<>();
List<Map<String,String> citiesStates = new ArrayList<>();
while(cityAndState.next()){
citiesStates.put("city", cityAndState.getString("city");
citiesStates.put("state", cityAndState.getString("state");
citiesAndStateCombinations.add(citiesStates);
}
Leaves an array with the last values printed 50 times.
[{city-Boise, state=Idaho}, {city=Boise, state=Idaho}.....50}
Each time it erases the previous value. I see why it is doing it, it's setting all the elements to the last value added which makes sense but is there a way to add the values so I am left with an array of the 50 cities and States?
The thing is you're implementing HashMap in the wrong way, or you misunderstood it: "A Map cannot contain duplicate keys and each key can map to at most one value."
What you're doing in the above code -
citiesStates.put("city", cityAndState.getString("city");
citiesStates.put("state", cityAndState.getString("state");
You're putting values with the same key "city" & "state" that's why it's overwriting the values.
The correct way to do this will be -
Map<String,String> citiesAndStateCombinations = new HashMap<>();
while(cityAndState.next()){
if(!citiesAndStateCombinations.containskey(cityAndState.getString("city"))){
citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
}
}
This will give you a city and state unique map now if you want it to be added to a list you can add this line at last but I don't see any use of it -
List<Map<String,String> citiesStates = new ArrayList<>();
citiesStates.add(citiesAndStateCombinations);
Please add this after closing the while loop.
----------EDITED----------
To achieve the solution which you're looking for you need to write something like this -
enter code here
while(----){
Map<String,String> citiesAndStateCombinations = new HashMap<>();
if(citiesAndStateCombinations.containsKey("city="+cityAndState.getString("city"))){
citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
citiesStates.add(citiesAndStateCombinations);
}
This will give you desired output -
[{city=XXXXXX=state=XXXXXX},
{city=XXXXXX=state=XXXXXX},
{city=XXXXXX=state=XXXXXX}]
Related
So I essentially want to go through all the elements in the arraylist and match it with the keys of each hashmap and for the values of the common keys I want to make a new arraylist.
Essentially if keygrades is on value 1, I want to check every hashmap with the key 1 and then extract all the values associated with that key and make a brand new arraylist with those values.
ArrayList <String> keygrades = new ArrayList<>();
HashMap <String,String> gradeA = new HashMap<>();
HashMap <String,String> gradeB = new HashMap<>();
HashMap <String,String> gradeC = new HashMap<>();
HashMap <String,String> gradeD = new HashMap<>();
This is what is in the hashmap:
keygrades = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
gradeA = {11=134, 1=100, 3=110, 4=120, 15=142, 5=130}
gradeB = {2=102, 3=103, 6=108, 8=109}
gradeC = {3=104, 5=105, 6=111}
gradeD = {3=122, 4=123}
For example for key 1 I want a new arraylist which would be (100,"","","") ""= empty string. For key 2 I want a new arraylist which would be ("",102,"","").It would continue going through hashmaps in order and inputting into new arraylist each time.
I recommend writing a method with this struture:
Create an ArrayList<ArrayList>, which will hold the outcoming
ArrayLists containing the different values for common keys.
Iterate over Arraylist containing the keys.
Create an ArrayList that will get the 4 values.
Check all 4 Hashmaps with the current key using HashMap.get(key).
If the outcome is null, you should add "" to your ArrayList, otherwise you
enter the value to the ArrayList inside the loop.
After it iterated through the ArrayList containing the keys. You should have an
ArrayList<ArrayList> holding exactly as much ArrayList containing the values for similar keys, as you ArrayList of keys size.
You can achieve this by transforming your maps into a stream of maps and extracting the values for a particular key.
List<String> values = Stream.of(gradeA,
gradeB,
gradeC,
gradeD)
.map(map -> map.getOrDefault("1", ""))
.collect(Collectors.toList());
To reuse this, you'll have to create a function that handles the combining of the maps and a function that extracts values from that stream of maps.
The example should get you on your way.
Given that I have the array of :
List<CustEnt> bulkList= CustRepo.fetchData();
//System.out.println(bulkList) -->
gives me :
CustEct(name:"kasis",age:24,surname:"kumar"),CustEct(name:"samika",age:50,surname:"sharma"),CustEct(name:"manoj",age:84surname:"kumar")
OR
bulkList.get(1) --> CustEct(name:"kasis",age:24,surname:"kumar")
I want to create a new array which is grouped by the 3rd parameter of surname object.
So that my array becomes
ArrayFinal = [CustEct(name:"kasis",age:24,surname:"kumar"),CustEct(name:"samika",age:50,surname:"sharma")],CustEct(name:"manoj",age:84surname:"kumar")
So that when we do .get(1) we would get object of kasis and samika.
Need the help in respective to java 8.
I heard that we can use the Map ,but can anyone give the small code sample or any other implementation guide.
A Map tracks key-value pairs.
Your key is the surname string.
Your value is a list of the CustEnt objects carrying that surname.
Map<String, List<CustEnt>>
Modern syntax with streams and lambdas makes for brief code to place your objects in a map.
Something like:
Map<String, List<CustEnt>> map = originalList.stream.collect(Collectors.groupingBy(CustEnt::getSurename));
Map<String, List<CustEntity>> NamesList
= bulkList.stream()
.collect(Collectors.groupingBy(CustEntity::getSurames));
for (Map.Entry<String, List<CustEntity>> entry: NamesList.entrySet()) {
ExcelGenerationService exp = new ExcelGenerationService( entry.getValue());
//service call
exp.export(entry.getKey());
}
I get from database some informations and I'd like to store it like:
Person[0] {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
...
So I can add more items, access items using position and after user show each position, remove it from array. eg: after user see array position 0 (Marie) info, remove array position 0 from memory.
What is the best way to do it? array, arraylist, arraymap...? How to declare, add and remove positions infos?
Thanks.
I guess you can use LinkedList may be, it provides constant O(1) time for adding item at last and removing first item.
You can use offer or add methods to add item and poll() to remove first item
You can do below operations
val list = LinkedList<String>()
list.add("Android") // add items to the end
list.add(5, "Hello") //adds item at mentioned position
list.poll() // removes first item
list.removeAt(4) //removes item at certain position
list.pollLast() // removes last item
To achieve what you are expecting, you could do something like this:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
map.put("name","Marie");
map.put("email","marie#marie.com");
map.put("adress","address marie");
data.add(map);
System.out.println(data.get(0));
For inserting multiple items:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
for(Class a : object)
{
map.put("name",a.name); //a.name is just from my imagination only. use your own aproach to get name.
map.put("email",a.email);
map.put("address",a.address);
data.add(map);
}
System.out.println(data.get(0));
Use ArrayList instead of Array for store data
String[] Person = {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
ArrayList<String> data = new ArrayList()<String>;
data.add(Person);
I am new in java arraylist. I have difficulties in creating arraylist. This is the example below. s1,s2,s3,s4,s5 is the category for people to choose and add number into it,
{[s1,0]}
{[s2,0]}
{[s3,0]}
{[s4,0]}
{[s5,0]}
For example, s1:2, s2:3, s1:3, s5:4, s3:2. How can i make the output to become like this
{[s1,5]}
{[s2,3]}
{[s3,2]}
{[s4,0]}
{[s5,4]}
I hope that someone can help me in this.
What you need here is a map. For example Map<String, Integer> map = new HashMap<String, Integer>();. Then to add you would do the following map.put("s1", 1);. An ArrayList is just an implementation of a list backed by an array and as such cannot have a key value pair. In order to update a value you would just do this:
int current = map.get("s1");
map.put("s1", current++);
If you need to track many values by a key then you would instead have a map of ArrayList, declared like so:
Map<String, ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
ArrayList<Integer> s1sValues = new ArrayList<Integer>();
s1s.add(1);
s1s.add(2);
map.put("s1", s1sValues);
//To add to existing
map.get("s1").add(3);//If you don't already have a reference
s1sValues.add(4);//If you do have the reference.
`
(Right click and open image in new tab to see it bigger)
nothing much to say but the code:
System.out.println("map add:" + parts[i].split("=")[0] + "=" + list);
map2.put(parts[i].split("=")[0], list);
prints out the exact same thing as what is added to the map but what is printed and what is on the map are completely different?
why is this?
You're adding the same list at each iteration, and hence the keys are referencing the same list (see figure below).
What you're actually doing is this :
You create a list containing the values [root, like] and you associate this list with the key root
In the second iteration, you clear the list and you add [eat, it] to this list and associate it with another key xsubj.
Since you did'nt create a new object, the keys root and xsubj point to the same list object and hence each change on the list will be reflected for all the keys that share it.
So that's why at the end you got this output.
Instead of calling clear(), create a new list at each iteration.
for(int i = 0; i < parts.length; i++){
list = new ArrayList<>();
list.add(...);
/**
* The code
**/
}