Size of HashMap not increasing - java

I go through a loop three times and call this method each time:
// class variable
private HashMap<String, ffMotorskillsSession> tempMap;
tempMap = new HashMap<String, ffMotorskillsSession>();
for loop {
addMotorskillsSession(session);
}
private void addMotorskillsSession(ffMotorskillsSession pSession) {
StringBuilder sb = new StringBuilder();
sb.append(pSession.period).append(":").append(pSession.section)
.append(":").append(pSession.class_name).append(":")
.append(pSession.semester).append(":").append(pSession.grade);
tempMap.put(sb.toString(), pSession);
Log.d("Size: ", String.valueOf(tempMap.size()));
}
Everytime I Log the size each time it passes thru it stays at one.
Can anyone see why?

A Map stores key/value pairs, with only one value per key. So if you're calling put with the same key multiple times, then it will correctly stick to the same size, only having a single entry for that key.

Related

Java 8 variable scope in lambda (Spark specific)

I would like to fill a map with a String as key and Row as value, my code:
private Map<String,Row> getMapFromDataset(Dataset<Row> dataset, List<String> mapColumns) {
Map<String, Row> map = new HashMap<>();
dataset.foreach((ForeachFunction<Row>) row ->
map.put(getKey(mapColumns,row),row) //This works
);
return map; //Map is empty when returning!
}
My getKey() method (although i think is not the cause of the issue):
private String getKey(List<String> mapColumns, Row row) {
StringBuffer sb = new StringBuffer(256);
for(String col : mapColumns){
sb.append((String)row.getAs(col));
}
return sb.toString();
}
Although it compiles and runs without errors, the map is always empty.
What i have noticed is that if i check the size of the map right after the first insertion, the map has size 1, so the items insertion works, but the returned map is empty
I also read that variables used within lambda should be final, this might explains the problem.
Any hint?
I found out that map initialization happens in Driver, while the lambdas foreach is sent to executors.

Java HashMap multiple keys with multiple values assigned flexible

I have a problem with my Java Code. I want to store multiple Values in one Key but I want to store them flexible. This means I read from a textfile and every line is one word. To store them, I want to build pairs of words. For example:
word1/word2
word2/word3
word3/word4
I have changed this method a little bit. I want to store the values of the keys in an arraylist. This means everytime when a new key comes up a new Arraylist and key will be stored, but if the key is in the map I want to store them in the list of this key. Is this possible?
We have to store them in a hashmap. But I can not get it to work:
private HashMap<String, ArrayList<String>> hmap = new HashMap<String, ArrayList<String>>();
private ArrayList<String> wort2;
public GrammelotH(String filename) throws IOException {
String fixWort = ".";
BufferedReader br = new BufferedReader(new FileReader(filename));
while (br.ready()) {
String line = br.readLine();
if (hmap.containsKey(fixWort)) {
hmap.put(fixWort, wort2.add(line));
}else {
hmap.put(fixWort, new ArrayList<String>().add(line));
}
fixWort = line;
}
br.close();
}
The problem is the put order. Has anybody of you an idea how to get
hmap.put(fixWort, new ArrayList<String>().add(line));
and
hmap.put(fixWort, wort2.add(line));
to work?
Thank you for your help!
Bye Bye!
I think I'd be looking at something like
List l = hmap.get(line);
if (l != null) {
l.add(line));
}else {
l = new ArrayList<String>();
l.add(line)
hmap.put(line, l);
}
So, you see if the map already contains the line you have just read from the file. If it does, you just add it to the associated list. If it doesn's.create a list, add line to it, and then add both to the Map.

Overwriting when using Map.putAll()

I am having some difficulty when using Map.putAll(). Instead of updating / adding particular records to my main map, it is overwriting the entries:
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> cache = new ConcurrentHashMap<String, ConcurrentHashMap<CardType, Card>>();
The three separate maps are generated as below:
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> businessCardCache = buildBusinesscardCacheValues(connection, getBusinessCards);
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> personalCardCache = buildPersonalcardCacheValues(connection, getPersonalCards);
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> socialCardCache = buildSocialcardCacheValues(connection, getSocialCard);
cache.putAll(businessCardCache);
cache.putAll(personalCardCache);
cache.putAll(socialCardCache);
What should happen is user ben for example should be the key and he should have a business a personal and a social card. What in fact happens is he only ends up with a socialCard as I assume it is the last to run and therefore overwrites the previous.
How should I approach modifying this?
Thanks
Your current initialization of cache would cause cache.putAll(personalCardCache); to replace the values added by cache.putAll(businessCardCache); for keys that appear in both maps.
If you want cache to contain all the cards of each user (taken from all 3 input maps), you should initialize it in a different way :
for (String key : businessCardCache.keySet()) {
ConcurrentHashMap<CardType, Card> cards = null;
if (cache.containsKey(key) {
cards = cache.get(key);
} else {
cards = new ConcurrentHashMap<CardType, Card>();
}
cards.putAll (businessCardCache.get(key));
}
Then you do the same for the other 2 maps.

Storing Data in a HashMap Java

I am trying to store data in a HashMap however I can only seem to store the very last item of the data source I am reading into the HashMap and I am unsure why.
Below is my code:
//Loops through the counties and stores the details in a Hashmap
void getCountyDetails(List<Marker>m){
HashMap t = new HashMap();
for(Marker county: countyMarkers){
println("county:" + county.getProperties());
t = county.getProperties();
}
println(t);
}
This line -> println("county:" + county.getProperties());
Outputs this:
county:{name=Carlow, pop=54,612}
county:{name=Cavan, pop=73,183}
county:{name=Clare, pop=117,196}
county:{name=Cork, pop=519,032}
county:{name=Donegal, pop=161,137}
county:{name=Dublin, pop=1,273,069}
county:{name=Galway, pop=250,541}
county:{name=Kerry, pop=145,502}
county:{name=Kildare, pop=210,312}
county:{name=Kilkenny, pop=95,419}
county:{name=Laois, pop=80,559}
county:{name=Letrim, pop=31,796}
county:{name=Limerick, pop=191,809}
county:{name=Longford, pop=39,000}
county:{name=Louth, pop=122,897}
county:{name=Mayo, pop=130,638}
county:{name=Meath, pop=184,135}
county:{name=Monaghan, pop=60,483}
county:{name=Offaly, pop=76,687}
county:{name=Roscommon, pop=64,065}
county:{name=Sligo, pop=65,393}
county:{name=Tipperary, pop=158,754}
county:{name=Waterford, pop=113,795}
county:{name=Westmeath, pop=86,164}
county:{name=Wexford, pop=145,320}
county:{name=Wicklow, pop=136,640}
I would like to store them in a HashMap.
This line -> println(t); outputs:
{name=Wicklow, pop=136,640}
Would appreciate any help on the matter guys. Basically it's just getting the list of data into the hashmap and currently only the last item in that list is being placed in.
If you want to print the properties of each Marker , move the println(t) line into the for loop, because at the moment t will point to the last used element's properties, because you just reassign it;s value each iteration of the cycle. To put an element in the map, use put(Key, Value) or putAll() methods instead
In java, you should use hashMap.put(key, value) to add new item into hash map.
In your code, you wrote HashMap t = new HashMap(); t = county.getProperties(); so you map value is actually been reassigned to country property each time.

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Categories

Resources