Java - Calculating the load factor - java

I am trying to calculate the load factor of my Hashtable and print out the result. However, when I run this, the load factor is equal to 2. This is currently the size of my map - so my method loadFactor is not quite working. Is there something obvious I am missing? ( i am fairly new to Java)
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Main {
Student student;
Hashtable next;
public Hashtable<String,Student> studentMap;
public static void main(String[] args){
Hashtable<String, String> studentMap = new Hashtable<>(10000, 0.75f);
studentMap.keySet().forEach((key) -> {
String value = studentMap.get(key);
System.out.println("Key = " + key + ", Value = " + value);
});
//adding values to array
studentMap.put("16012804", "Jennifer");
studentMap.put("13747732", "Beatrice");
studentMap.put("14058392", "Bob");
Set set = studentMap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mapentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mapentry.getKey() + " & Value is: ");
System.out.println(mapentry.getValue());
}
//Get values based on key
String var= studentMap.get("16012804");
System.out.println("Value at index 1 is: "+var);
// Remove values based on key
studentMap.remove("16012804");
System.out.println("Map key and values after removal:");
Set set2 = studentMap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mapentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mapentry2.getKey() + " & Value is: ");
System.out.println(mapentry2.getValue());
}
Set keyset = studentMap.keySet();
System.out.println("Key set values are:" + keyset);
boolean val = studentMap.isEmpty();
System.out.println("Is hash map empty: " + val);
System.out.println("Size of the Hashtable " + studentMap.size());
System.out.println("Load Factor: " + loadFactor(studentMap));
System.out.println("Hash: " + studentMap.hashCode());
System.out.println("Size of map is now: " + mapcapacity(studentMap));
}
public static float loadFactor(Map studentMap){
int count=0;
float load;
for(int i=0; i<studentMap.size(); i++){
count += studentMap.size();
}
load = count/(float)studentMap.size();
return load;
}
//if the size of the map is greater than the map capacity * load factor - then double the size of map.
public static Integer mapcapacity(Map studentMap){
Integer initCapacity=2;
float loadFactor=0.75f;
boolean capacityFound=false;
Integer capacity=initCapacity;
Integer size=studentMap.size();
while(!capacityFound){
if(size>capacity*loadFactor){
capacity=capacity*2;
}
else {
capacityFound=true;
}
}
return capacity;
}
public int hash(String key){
return (Math.abs(key.hashCode())) % studentMap.size();
}
}

Related

Nested HashMap value multiplication -Java

From the code below is it possible to get
apple 1.50
pears 6
if not then at least 1.50 and 6? I have done a few things to achieve that / read a few stack over flow but now sure how to do that. Thanks in advance for your time/comments. emphasized text
public class RandomCheck {
public static void main(String[] args) {
//Keep Track of Fruit, Quantity and Price per item
Map<String, Map<Integer, Double>> mapOuter = new HashMap<String, Map<Integer, Double>>();
//Keep Track of Quantity and Price per item
Map<Integer, Double> mapInner = new HashMap<Integer, Double>();
mapInner.put(2, .75);
mapInner.put(4, 1.25);
mapOuter.put("apple", mapInner);
mapOuter.put("pears", mapInner);
//ToDo: Get Final price of this purchase all together will be (2*.$75) + (4* $1.25)= $6.5
double finalTotal = 0;
for (Map.Entry<Integer, Double> innerData : mapInner.entrySet()) {
finalTotal = finalTotal + (innerData.getKey() * innerData.getValue());
}
System.out.println("Total price " + finalTotal);
//ToDo:Get itemized total, for Apple it will be 2* $.75 and for pears 4* $1.25
double totalByItem = 0;
/* for (Map.Entry<String, Map<Integer, Double>> outerData : mapOuter.entrySet()) {
for (Map.Entry<Integer, Double> innerData : mapInner.entrySet()) {
// System.out.println(" KEY Outer "+ outerData.getKey() + " KEY Inner " + innerData.getKey() + " Value Inner " + innerData.getValue());
totalByItem = totalByItem + (innerData.getKey() * innerData.getValue());
}
}
System.out.println("By item price " + totalByItem);*/
/* Iterator <k> itr= map.keySet().iteraotr;
while(itr.hasNext()){
K key = its.next();
V value= map.get(key);
}*/
}
}
Shouldn't your Maps be structured like this:
Map<String, Integer> quantity = new HashMap<>();
quantity.put("apple", 2);
quantity.put("pears", 4);
Map<String, Double> price = new HashMap<>();
price.put("apple", .75);
price.put("pears", 1.25);
Then you can do something like:
for(String fruit : quantity.keySet())
{
int fruitQuantity = quantity.get(fruit);
double fruitPrice = price.get(fruit);
// ...
}
By the way, pears total should be 5 not 6.

java.util.HashMap.get method returns 2 values for one key

I made a Graph class which uses a HashMap> to keep nodes as keys and corresponding edges as values.
public class GraphAL {
private HashMap<Integer, ArrayList<Integer>> adjList;
private ArrayList<Integer> vertices;
int numberOfNodes;
boolean visited[];
GraphAL(HashMap<Integer, ArrayList<Integer>> adjList,
ArrayList<Integer> vertices, int numberOfNodes){
this.adjList = adjList;
this.vertices = vertices;
this.numberOfNodes = numberOfNodes;
visited = new boolean[this.numberOfNodes];
}
public HashMap<Integer, ArrayList<Integer>> getAdjList() {
return adjList;
}
public ArrayList<Integer> getVertices() {
return vertices;
}
public int getNumeberOfNodes()
{
return numberOfNodes;
}
public boolean[] getVIsitedNodes()
{
return visited;
}
public void setVisitedNodesToTrue(int node)
{
visited[node] = true;
}
}
I made then a method to reverse the graph.
The problem is that java.util.HashMap.get method returns 2 values instead of one although my keys are unique. This leads to adding an edge to more than the exact node where I want to add an edge.
public static GraphAL reverseGraph(GraphAL g)
{
HashMap<Integer, ArrayList<Integer>> revAdjList = new HashMap<Integer, ArrayList<Integer>>();
ArrayList<Integer> revVertices = new ArrayList<Integer>();
System.out.println("Printing in for loop");
for(Integer x:g.getVertices())
{
System.out.println("x = " + x);
ArrayList<Integer> edges = new ArrayList<Integer>();
edges.add(x);
System.out.println("Edges: ");
for(Integer m:edges)
{
System.out.print(m + " ");
}
for(Integer y:g.getAdjList().get(x))
{
System.out.println("y = " + y);
if(!revVertices.contains(y))
{
revVertices.add(y);
System.out.println("RevVertices: ");
for(Integer n:revVertices)
{
System.out.print(n + " ");
}
}
if(revAdjList.containsKey(y))
{
for(Integer o:revAdjList.get(5))
{
System.out.println(5 + " contains " + o);
}
System.out.println("adding " + x + " to " + y);
revAdjList.get(y).add(x);
for(Integer o:revAdjList.get(y))
{
System.out.println(y + " contains " + o);
}
for(Integer o:revAdjList.get(5))
{
System.out.println(5 + " contains " + o);
}
}
else
{
revAdjList.put(y, edges);
System.out.println("putting " + x + " at " + y);
}
System.out.println("Current AdjList: ");
for(Integer h:revVertices)
{
System.out.print("vertice is: " + h + " ");
for(Integer j:revAdjList.get(h))
{
System.out.print("edge : " + j + " ");
}
System.out.println();
}
}
}
System.out.println("Done printing in for loop");
GraphAL revGraph = new GraphAL(revAdjList, revVertices, g.getNumeberOfNodes());
return revGraph;
}
Sorry for all the print.ln's but I wanted to be sure where the problem is occurring. It looks like revAdjList.get(y).add(x), where y=6 and x=3, is returning the corresponding ArrayList from key 6 like I want but also from key 5. Ofc this leads to adding edge 3 to 6 like I want but it's also adding it to 5 as well.
Thoughts?
x = 3
Edges:
3 y = 6
5 contains 8
adding 3 to 6
6 contains 8
6 contains 3
5 contains 8
5 contains 3
adding 3 to 6
Current AdjList:
vertice is: 1 edge : 7
vertice is: 2 edge : 5
vertice is: 3 edge : 9
vertice is: 7 edge : 9
vertice is: 4 edge : 1
vertice is: 5 edge : 8 edge : 3
vertice is: 6 edge : 8 edge : 3
The problem happens on this line
for (Integer j : revAdjList.get(h)) {
System.out.print("edge : " + j + " ");
}
Lets point out the issue here and why its printing out the "edge" twice
revAdjList.get(h)
returns a collection of Integer not a single Integer so it can have as many integer values as you want since you are defining it as a collection and not a single-ton.
You are adding multiple edges from here
for (Integer m : edges) {
System.out.print(m + " ");
}
If you just want 1 edge, don't make edges an array.
HashMap<Integer, ArrayList<Integer>> revAdjList = new HashMap<>();
should be defined as
HashMap<Integer, Integer> revAdjList = new HashMap<>();
After you have done that, you can remove the loops and clean up the code to work with the new syntax.

Value For A Key In A Hashmap Being Set To Value Of Another Key

I am having issues with the values of different keys in a hashmap I created. Somehow, the values are being overwritten by the most current added value.
For example:
map.put("String1", "123")
map.put("String2", "456")
System.out.println(map.get("String1")); //would print 456
My hashmap is:
Map<String, Testing> systems = new HashMap<>();
Testing:
class Testing {
private double[] ap;
private double[] dcg;
private double[] ndcg;
public Testing(double[] _ap, double[] _dcg, double[] _ndcg){
ap = _ap;
dcg = _dcg;
ndcg = _ndcg;
}
public double[] getAp(){
return ap;
}
public double[] getDcg(){
return dcg;
}
public double[] getNdcg(){
return ndcg;
}
}
Here is the problem (f is a File):
systems.put(f.getName(), new Testing(ap, dcg, ndcg));
if(f.getName().equals("input.Flab9atdnN.gz") ||
f.getName().equals("input.apl9lt.gz")) {
System.out.println(f.getName() + ": " +
systems.get(f.getName()).getAp()[5]);
}
if(f.getName().equals("input.Flab9atdnN.gz")) {
System.out.println(f.getName().equals("input.Flab9atdnN.gz"));
double temp = systems.get("input.apl9lt.gz").getAp()[5];
double temp2 = systems.get("input.Flab9atdnN.gz").getAp()[5];
System.out.println("input.Flab9atdnN.gz: " + temp2 + ". input.apl9lt.gz:
" + temp);
}
The first print gives different values for key "input.Flab9atdnN.gz" and key "input.apl9lt.gz".
System.out.println(f.getName() + ": " + systems.get(f.getName()).getAp()
[5]);
The last print statement gives the same value for key "input.Flab9atdnN.gz" but gives key "input.apl9lt.gz" key "input.Flab9atdnN.gz"'s value. Key "input.Flab9atdnN.gz" is added to the hashmap after key "input.apl9lt.gz" thus anything added after key "input.Flab9atdnN.gz" would give that new keys value to "input.Flab9atdnN.gz" as well.
double temp = systems.get("input.apl9lt.gz").getAp()[5];
double temp2 = systems.get("input.Flab9atdnN.gz").getAp()[5];
System.out.println("input.Flab9atdnN.gz: " + temp2 + ". input.apl9lt.gz: " +
temp);
Any clue why this is and any possible work around? I tried doing something similar with lists and had the same problem. I tried not using Testing as well.
Thank you.
Edit (for inputs):
input.apl9lt.gz
0.160837098024862
0.03075251487336594
0.22437008086531643
0.1971910732696186
0.26775040012743095
9.256258391747239E-4
0.1348288884102969
0.04098977989693765
0.22076261792825694
0.14351330413359978
0.4326923076923077
0.07127127472804279
4.552325182365065E-5
0.010058991520632703
0.013241228159087674
0.010137295467368818
0.16308220490382738
0.013974532767649097
0.1591821903406855
0.03546054590978735
0.017811035142771457
0.09931683119953653
0.0012300123001230013
3.2100667693888034E-5
0.13463869607114665
0.056660951442691745
0.009024064171122994
0.00111158621285874
0.19147531389263409
6.058415656054187E-4
0.15122464967762936
0.017945455244915694
0.24100308685261787
6.295914132164171E-4
0.41666666666666663
0.16054778554778554
0.12606805722666745
0.03122700118062138
0.05840908368719257
0.06151876506910154
8.167932696234583E-5
0.48663786619303134
0.0017420658249683476
0.20520161886380303
7.111269849728675E-5
0.1157176972265951
0.28587824256374156
0.032836748137528377
0.04182754182754183
0.02944176265259386
input.Flab9atdnN.gz
0.4550531747779656
0.11354712610736152
0.4465970245283123
0.39990864084973815
0.23410193071725469
8.08015513897867E-5
0.11287817139653589
0.02255268670973833
0.30038335608865446
0.21267974099603318
0.6041666666666666
0.15726821262566176
0.15690222729126874
1.5053439710973956E-4
0.0843584401155248
0.5027027027027027
0.1873237718924946
0.005660813678763912
0.012321170992537366
0.0529994153272247
0.04489848129896188
0.016508461433080466
0.0
1.0736065674698053E-4
0.07164253590778259
0.14083889573189318
0.024676040805073064
0.16099898114516484
0.16509562037628656
0.06488409960391041
0.22263263699157246
0.0568843663526689
0.4175364417422477
0.1106842493991619
0.15555555555555556
0.5416666666666666
0.4654817731306396
0.0930344930767678
0.344114561968089
0.1882981402539536
0.11698973634619976
0.4533746137676584
0.3389765988389732
0.475199277730597
0.08708693608991427
0.34790332410690694
0.035929746042875826
0.08056424630498706
0.20352743561030237
0.12758565977230674
Read these into a double array (size 50). To use the Testing class, just remove dcg and ndcg.
First of all:
import java.util.HashMap;
public class MapPutExample {
public final static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("String1", "123");
map.put("String2", "456");
System.out.println(map.get("String1")); //would print 456
}
}
prints
123
So: No it's not.
You haven't provided the actual code where we can see how you add elements to the map but given the fact that Testing contains arrays I suppose that you don't initiialize new arrays when setting its values from the file. So you do something like this:
import java.util.HashMap;
public class MapPutExample {
public final static void main(String[] args) throws Exception {
HashMap<String, char[]> map = new HashMap<>();
char[] buffer = new char[10];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (char) ('a' + i);
}
map.put("String1", buffer);
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (char) ('k' + i);
}
map.put("String2", buffer);
System.out.println(map.get("String1")); //would print klmnopqrst
}
}
This actually prints
klmnopqrst
You need to create new arrays and set these to the Testing instances that you add to the map:
import java.util.HashMap;
public class MapPutExample {
public final static void main(String[] args) throws Exception {
HashMap<String, char[]> map = new HashMap<>();
char[] buffer = new char[10];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (char) ('a' + i);
}
map.put("String1", buffer);
buffer = new char[10];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (char) ('k' + i);
}
map.put("String2", buffer);
System.out.println(map.get("String1")); //would print klmnopqrst
}
}
This is printing
abcdefghij

compare two successive hasmap value

I need to compare for a single hashmap two by two successive values like in the example below:
key is: Nature ---- Value is: 2
key is: duck ---- Value is: 3
key is: sheep ---- Value is: 3
key is: WoodTable ---- Value is: 4
key is: PVCdoor ---- Value is: 4
What I'm asking for, is how can I compare :
the value of Nature with the value of duck
the value of duck of the value of sheep
the value of sheep with the value of woodTable
the value of woodTable with the value of PVCdoor
.... etc
I tried but I can't get the result I need. Please if you have any idea I need your help;
This is the function I use but the result isn't at all what I need as an output.
Thank you
public Map<String, Integer> setCoefffils(Map<String, Integer> map){
Map.Entry<String,Integer> entry=map.entrySet().iterator().next();
this.listCoeffConceptfilsfinal.put(entry.getKey(), coeffFils);
Set<Entry<String, Integer>> setHm = map.entrySet();
java.util.Iterator<Entry<String, Integer>> it = setHm.iterator();
Entry<String, Integer> e = it.next();
for( Entry<String, Integer> ee : setHm){
// Entry<String, Integer> eeee = it.next();
// for( Entry<String, Integer> eeee : setHm){
System.out.println("key current is: "+ee.getKey() + " ---- Value is: " + ee.getValue());
System.out.println("key following is: "+e.getKey() + " ---- Value is: " + e.getValue());
if(ee.getValue().equals(e.getValue()))
System.out.println(""+ee.getValue() + " et " + e.getValue()+" sont égaux ");
else
System.out.println(" ne sont pas égaux ");
// }
return this.listCoeffConceptfilsfinal;
}
One solution is to store all the keys in a list, then access them one after the other.
public static void foo(Map<String, Integer> map) {
Set<String> keySet = map.keySet();
String lastKey = null;
for (String key : keySet) {
if (null == lastKey) {
lastKey = key;
continue;
}
if (map.get(key).equals(map.get(lastKey))) {
System.out.println("Les valeurs associées aux clés " + lastKey + " et " + key + " sont égales.");
} else {
System.out.println("Les valeurs associées aux clés " + lastKey + " et " + key + " sont différentes.");
}
lastKey = key;
}
}
But be aware : Maps doesn't always guarantee that the keys stay in insertion order. Thus, your comparison could be false. If you want to conserve insertion order, you have to use a LinkedHashMap.
With key order
CODE:
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
/**
* Write a description of class sumAndMax here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class compareMap
{
public static void main(String[] args){
Map<String, Integer> map = initializeMap();
compareMaps(map);
}
private static void compareMaps(
Map<String, Integer> map)
{
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
String leftKey = "";
String rightKey = "";
int leftValue = -1;
int rightValue = -1;
while (it.hasNext()) {
// Get values
Map.Entry<String, Integer> pair = it.next();
leftKey = rightKey;
leftValue = rightValue;
rightKey = pair.getKey();
rightValue = pair.getValue();
if(!leftKey.equals("")){
// Compare keys
System.out.println("Comparing key "+leftKey+" with key "+rightKey);
System.out.println("Result: "+leftKey.equals(rightKey));
// Compare values
System.out.println("Comparing value "+leftValue+" with value "+rightValue);
System.out.println("Result: "+(leftValue==rightValue));
}
}
}
private static Map<String, Integer> initializeMap(){
// Use Tree map for have a key ordered map !!!
Map<String, Integer> map = new TreeMap<>();
map.put("keyA",3);
map.put("keyB",4);
map.put("keyC",8);
map.put("keyD",8);
map.put("keyE",89);
map.put("keyF",4);
map.put("keyG",4);
return map;
}
}
RESULT:
Comparing key keyA with key keyB
Result: false
Comparing value 3 with value 4
Result: false
Comparing key keyB with key keyC
Result: false
Comparing value 4 with value 8
Result: false
Comparing key keyC with key keyD
Result: false
Comparing value 8 with value 8
Result: true
Comparing key keyD with key keyE
Result: false
Comparing value 8 with value 89
Result: false
Comparing key keyE with key keyF
Result: false
Comparing value 89 with value 4
Result: false
Comparing key keyF with key keyG
Result: false
Comparing value 4 with value 4
Result: true

Getting the maximum size of a list from other class

I am trying to get the maximum size of a list on the other class to set it as a maximum size in a loop to another class. As a result, it doesn't read the size that i get. here is the code:
Users.java
private void populateList() {
CusInfoManipulator c = new CusInfoManipulator(this);
int max = c.getMaxSize();
for(int x = 0;x<max;x++){
HashMap<String, String> value= new HashMap<String,String>();
c.listData(x);
value.put("username", "Username: " + c.getUserL());
value.put("name","Customer Name: "+ c.getFnameL() +" "+ c.getLnameL());
value.put("address", "Address: " + c.getAddressL());
value.put("landmark", "Landmarks: " + c.getLandmrkL());
value.put("num1", "Contact Number 1: " + c.getNumL());
value.put("num2","Contact Number 2: " + c.getNum2L());
list.add(value);
}
}
the maximum size of the list from parse cloud:
List<ParseObject> searchItems = query.find();
int max = searchItems.size();
public int getMaxSize() {
return max;
}
Can someone please help me to figure out what went wrong in my code and why it doesn't get the max size?
Not sure but maybe you should do:
public int getMaxSize()
{
List<ParseObject> searchItems = query.find();
int max = searchItems.size();
return max;
}
getMaxSize method should return something like list.size() instead of a constant value

Categories