Add data into arraylist based on 1st column - java

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.
`

Related

Map object keeps getting overwritten when adding

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}]

Go through multiple hashmaps of different sizes to extract values with common keys

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.

Create multiple Lists from one (Group List's Objects by a specific field)

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());
}

How To Access hash maps key when the key is an object

I cannot seem to figure out how to access the values of my hashmap
What I am basically trying to do is create a hashmap with an array as one of the values like json style.. If that makes sense?
So I want something like hash{key: value1, value2, value3, [number1,number2]}
and be able to access it like (pseudocode:) hash.get(3).get(1)
public class WebSearch {
readFile.ReadFile xfile = new readFile.ReadFile("inputgraph.txt");
HashMap webSearchHash = new HashMap();
ArrayList belongsTo = new ArrayList();
ArrayList keyphrase = new ArrayList();
public WebSearch() {
}
public void createGraph()
{
HashMap <Object, ArrayList<Integer> > outlinks = new HashMap <Object, ArrayList<Integer>>();
for (int i = 0; i < xfile.getNumberOfWebpages(); i++ )
{
keyphrase.add(i,xfile.getKeyPhrases(i));
outlinks.put(keyphrase.get(i), xfile.getOutLinks(i));
}
}
keyphrases is an ArrayList
this is my output of System.out.print(outlinks);
{[education, news, internet]=[0, 3], [power, news]=[1, 4], [computer, internet, device, ipod]=[2], [university, education]=[5]}
How would I go about getting say just this: [education, news, internet]=[0, 3]
I have tried:
outlinks.get(xfile.getKeyPhrases(i))
xfile.getKeyPhrases(0) would for example return [education, news, internet]
You can get the key set (Map.keySet()) of the map first; outlinks.keySet()
Then you can use these keys on your map to get your entries (values of the keys)
You haven't posted enough of the surrounding code for your question to be entirely clear, but look at the Javadocs for Map. You will probably get what you want by iterating over outlinks.values().
I recommend to use a customized object and use it inside your collections.
You may create a POJO/Bean class and overwrite the toString method with the details that you want, for instance the a iterate over items inside a array.
When you use it to print or display the toString method will be call.
The following link show you some ideas:
http://www.javapractices.com/topic/TopicAction.do?Id=55
http://en.wikipedia.org/wiki/Plain_Old_Java_Object
You can access the keys of any HashMap using Map.keySet() method.
Also note that java.util.HashMap is unordered. HashMap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
You would like to relook at the structure of your HashMap, you are having ArrayList as your key.

Adding to a hashmap inside of a hashmap

Here is what I have:
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
But I am having trouble adding values to this, because the inner hashmap doesn't have a name (note: it isn't supposed to). I'm actually trying to add an array list to the first Integer in HashMap So I am trying something like:
data.put(var, data.get(array.get(x), y));
Which it very much doesn't like and I'm totally clueless as to how to do it.
Note that
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
only creates the "outer" HashMap instance. After this statement you have an empty HashMap that takes Strings as keys and HashMap<Integer, Integer> as value.
You can add an instance of HashMap<Integer, Integer> to data with this:
data.put("myKey", new HashMap<Integer, Integer>());
After that you can add Integer values to the second HashMap:
data.get("myKey").put(123, 456); // use 123 as key and 456 as value
Get the values back:
data.get("myKey").get(123); // returns 456
You have to get the inner hash map first:
HashMap<Integer,Integer> innerData = data.get(var);
Then you can put your value into it:
innerData.put(x, y);
Just do it like this:
data.put( var, new HashMap(intKey, intVal));
where intKey and intVal are Integer type Key and Integer type value.
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
((Map)data.get( "keyname" )).get(1);
and subsequently:
((Map)data.get( "keyname" )).get( 1 ).put(2);

Categories

Resources