Addition table guava and arraylist - java

I have this program and I want to gather values in ArrayList operatCible and values in Table employeeYearsOfService and I want to stock the result in HashMap<String,integer> witch contains RowKey and result.
I don't know how to do it. This what I want
Code
public class collaborativAlgorithme {
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
public static void main(String[] args) {
List<Double> operatCible = new ArrayList<Double>();
operatCible.add(4.1);
operatCible.add(5.0);
System.out.println(operatCible);
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
employeeYearsOfService.put("AT&T", "Stacy Lerner", 1.4);
employeeYearsOfService.put("Microsoft", "Stacy Lerner", 3.5);
employeeYearsOfService.put("Microsoft", "Bill Smith", 13.2);
employeeYearsOfService.put("Google", "Stacy Lerner", 11.5);
employeeYearsOfService.put("AT&T", "Bill Smith", 2.0);
employeeYearsOfService.put("Google", "Bill Smith", 9.75);
System.out.println(employeeYearsOfService.rowKeySet());
HashMap<String,Integer> result=new HashMap<String,Integer>;
System.out.println(employeeYearsOfService);
Map<String, Double> attEmployees = employeeYearsOfService.row("AT&T");
for (Map.Entry<String, Double> employee : attEmployees.entrySet()) {
// what i do??
// sum values arraylist and values table
System.out.println("Employee Name: " + employee.getKey() + ", Years
of Service: " + employee.getValue());
}
}
}

I solved my problem
And I add something else as (sqrt)....
this is the code
int k = 0;
Double sum = 0.0;//cosine similarity
Double sum2 = 0.0;
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
HashMap<String, Double> hm = new HashMap<String, Double>();
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() * operatCible.get(k);
sum2+=employee.getValue();
k++;
}
k = 0;
System.out.println(sum);
System.out.println("----");
System.out.println(sqrt(sum2));
hm.put(key, sum);
sum = 0.0;
System.out.println(hm);
}
}

you ca dou that
HashMap<String, Double> hm = new HashMap<String, Double>();
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() + operatCible.get(k);
k++;
}
k = 0;
System.out.println(sum);
hm.put(key, sum);
}

Related

Using Hashmaps to compare keys and values and add together values based on similar keys

So i was wondering how and if it was possible using Hashmaps, one containing only strings and the other containing a similar string key but a float value, to compare them and then from that comparison print out the amount of similar values in the first hashmap, and then the float from the second hashmap added together when their keys/values line up. Example below that should clarify what i mean and to do this dynamically.
CODE
HashMap<String, String> hmap = new HashMap<>();
HashMap<String, Float> h2map = new HashMap<>();
hmap.put("order1", "pending");
hmap.put("order2", "cancelled");
hmap.put("order3", "pending");
h2map.put("order1", (float) 19.95);
h2map.put("order2", (float) 19.95);
h2map.put("order3", (float) 39.9);
Set <String> singles = new HashSet<>(h2map.values());
if(h2map.keySet().equals(hmap.keySet())) {
// below prints out the states and amount of the states but how can i get the float values from hmap to be added together for the similar states and printed with their respective state?
for(String element : singles) {
System.out.println(element + ": " + Collections.frequency(hmap.values(), element));
}
}
Current Output
pending: 2
cancelled: 1
Desired Output
pending: 2 $59.85
cancelled 1 $19.95
Is this what you want?
public static void main(String[] args) {
HashMap<String, String> hmap = new HashMap<>();
HashMap<String, Float> h2map = new HashMap<>();
hmap.put("order1", "pending");
hmap.put("order2", "cancelled");
hmap.put("order3", "pending");
h2map.put("order1", 19.95f);
h2map.put("order2", 19.95f);
h2map.put("order3", 39.9f);
Map<String, DoubleSummaryStatistics> grouping = hmap
.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.summarizingDouble(e -> h2map.get(e.getKey()))));
grouping.forEach((key, value) -> System.out.println(key + ": " + value.getCount() + " " + value.getSum()));
}
Note that there is no summarizing statistics collector for BigDecimal and this code works only with Float or Double. But for money calculations better use BigDecimal. It's possible to implement the custom collector if needed )
I have replaced the use of Float with BigDecimal for better accuracy. Also I used two maps, one for holding the summed value and the other for count:
public static void main(String[] args) {
HashMap<String, String> hmap = new HashMap<>();
HashMap<String, BigDecimal> h2map = new HashMap<>();
hmap.put("order1", "pending");
hmap.put("order2", "cancelled");
hmap.put("order3", "pending");
h2map.put("order1", new BigDecimal("19.95"));
h2map.put("order2", new BigDecimal("19.95"));
h2map.put("order3", new BigDecimal("39.9"));
//Map for holding sum
HashMap<String, BigDecimal> sum = new HashMap<>();
for(String key : h2map.keySet()){
if(hmap.get(key) != null){
String value = hmap.get(key);
if(sum.get(value) == null){
sum.put(value, h2map.get(key));
}else{
sum.put(value, (sum.get(value).add(h2map.get(key))));
}
}
}
//Map for holding count
HashMap<String, BigDecimal> countMap = new HashMap<>();
for(Iterator<Map.Entry<String, BigDecimal>> itr = sum.entrySet().iterator(); itr.hasNext(); ){
Map.Entry<String, BigDecimal> entry = itr.next();
String key = entry.getKey();
int count = Collections.frequency(hmap.values(), key);
countMap.put((key + count), sum.get(key));
itr.remove();
}
//For GC
sum = null;
countMap.forEach((k, v) -> System.out.println(k + " " + v));
}

trying to calculate profit in java

The first parameter is a HashMap representing the selling price of each item in our store (that is given).
The second parameter is also a HashMap but this one represents our cost for us to purchase each item for our inventory.
The third parameter is also a HashMap but this one representing a customers cart.
This method computes and returns total profit for this day. Note that the profit of selling an item is the cost of a customer (prices in the first parameter) minus our cost to purchase the item our inventory (second parameter). In all computation, use the following prices.
This is what I did, not sure what I did wrong. Also is there a way I can do this without using entryset?
public static double computeProfit(HashMap<String, Double> sellingPrice, HashMap<String, Double> inventory, ArrayList<HashMap<String, Integer>> orders) {
double ans = 0;
for (HashMap<String, Integer> order : orders) {
for (Map.Entry<String, Integer> itemToQuantity : order.entrySet()) {
String item = itemToQuantity.getKey();
Integer quantityPurchased = itemToQuantity.getValue();
inventory.put(item, inventory.get(item) * quantityPurchased);
}
}
for (Entry<String, Double> itemInInventory : inventory.entrySet()) {
String itemName = itemInInventory.getKey();
Double reQuantity = itemInInventory.getValue();
ans = ans -(sellingPrice.get(itemName)+ reQuantity);
}
return ans;
}
public static ArrayList<HashMap<String,Integer>> allOrders(){
ArrayList<HashMap<String, Integer>> allOrders = new ArrayList<>();
HashMap<String, Integer> cart0 = new HashMap<>();
cart0.put("frozen dinner", 4);
cart0.put("yogurt", 4);
cart0.put("milk", 3);
allOrders.add(cart0);
HashMap<String, Integer> cart1 = new HashMap<>();
cart1.put("yogurt", 4);
cart1.put("strawberries", 3);
cart1.put("apples", 4);
allOrders.add(cart1);
return allOrders;
}
public static HashMap<String,Double>sellingPrice(){
HashMap<String,Double>priceList = new HashMap<String,Double>();
priceList.put("eggs", 1.79);
priceList.put("orange juice",2.5);
priceList.put("yogurt",1.99);
priceList.put("bread",2.49);
priceList.put("butter",2.39);
priceList.put("peppers",1.49);
priceList.put("chips",2.95);
priceList.put("chocolate chips",2.39);
priceList.put("popcorn",1.99);
priceList.put("tomato sauce",0.99);
priceList.put("frozen pizza",5.49);
priceList.put("milk",2.09);
priceList.put("bananas",0.49);
priceList.put("hot dog",1.29);
priceList.put("relish",0.99);
priceList.put("frozen dinner",2.5);
priceList.put("cereal",3.25);
priceList.put("tuna fish",0.99);
priceList.put("coffee",2.0);
priceList.put("pasta",0.99);
priceList.put("strawberries",3.5);
priceList.put("apples",1.29);
priceList.put("sugar",1.99);
priceList.put("ketchup",2.89);
return sellingPrice();
}
public static HashMap<String, Double> purchasePrice(){
HashMap<String,Double>cart = new HashMap <String,Double>();
cart.put("eggs", 1.2);
cart.put("orange juice", 1.0);
cart.put("yogurt", 1.0);
cart.put("bread", 1.5);
cart.put("butter", 1.95);
cart.put("peppers", 0.99);
cart.put("chips", 0.9);
cart.put("chocolate chips", 1.79);
cart.put("popcorn", 0.99);
cart.put("tomato sauce", 0.4);
cart.put("frozen pizza", 2.6);
cart.put("milk", 1.89);
cart.put("bananas", 0.39);
cart.put("hot dog", 0.79);
cart.put("relish", 0.49);
cart.put("frozen dinner", 1.5);
cart.put("cereal", 1.55);
cart.put("tuna fish", 0.49);
cart.put("coffee", 0.6);
cart.put("pasta", 0.5);
cart.put("strawberries", 1.99);
cart.put("apples", 0.99);
cart.put("sugar", 1.5);
cart.put("sugar", 0.98);
return purchasePrice();
}
public static void main(String [] args){
computeProfit(sellingPrice(),purchasePrice(),allOrders());
}
I also tried this , what am I doing wrong here?
public static double ComputeProfit(HashMap sellingPrice, HashMap inventory, ArrayList> orders) {
double ans = 0;
int i =0, j = 0;
for(i=0;i< orders.size();i++) {
HashMap<String,Integer> temp = orders.get(i);
for (j=0;j < temp.size();j++) {
String item = temp.getKey(j);
Integer quantityPurchased = temp.getValue(j);
inventory.put(item, inventory.get(item) * quantityPurchased);
}
}
int k=0 ;
for (k =0 ; k< inventory.size();k++) {
HashMap <String,Integer>itemInInventory = inventory.get(k);
String itemName = itemInInventory.getKey(k);
Double reQuantity = itemInInventory.getValue(k);
ans = ans -(sellingPrice.get(itemName)+ reQuantity);
}
return ans;
}
public static ArrayList<HashMap<String,Integer>> allOrders(){
ArrayList<HashMap<String, Integer>> allOrders = new ArrayList<>();
HashMap<String, Integer> cart0 = new HashMap<>();
cart0.put("frozen dinner", 4);
cart0.put("yogurt", 4);
cart0.put("milk", 3);
allOrders.add(cart0);
HashMap<String, Integer> cart1 = new HashMap<>();
cart1.put("yogurt", 4);
cart1.put("strawberries", 3);
cart1.put("apples", 4);
allOrders.add(cart1);
return allOrders;
}
public static HashMap<String,Double>sellingPrice(){
HashMap<String,Double>priceList = new HashMap<String,Double>();
priceList.put("eggs", 1.79);
priceList.put("orange juice",2.5);
priceList.put("yogurt",1.99);
priceList.put("bread",2.49);
priceList.put("butter",2.39);
priceList.put("peppers",1.49);
priceList.put("chips",2.95);
priceList.put("chocolate chips",2.39);
priceList.put("popcorn",1.99);
priceList.put("tomato sauce",0.99);
priceList.put("frozen pizza",5.49);
priceList.put("milk",2.09);
priceList.put("bananas",0.49);
priceList.put("hot dog",1.29);
priceList.put("relish",0.99);
priceList.put("frozen dinner",2.5);
priceList.put("cereal",3.25);
priceList.put("tuna fish",0.99);
priceList.put("coffee",2.0);
priceList.put("pasta",0.99);
priceList.put("strawberries",3.5);
priceList.put("apples",1.29);
priceList.put("sugar",1.99);
priceList.put("ketchup",2.89);
return sellingPrice();
}
public static HashMap<String, Double> purchasePrice(){
HashMap<String,Double>cart = new HashMap <String,Double>();
cart.put("eggs", 1.2);
cart.put("orange juice", 1.0);
cart.put("yogurt", 1.0);
cart.put("bread", 1.5);
cart.put("butter", 1.95);
cart.put("peppers", 0.99);
cart.put("chips", 0.9);
cart.put("chocolate chips", 1.79);
cart.put("popcorn", 0.99);
cart.put("tomato sauce", 0.4);
cart.put("frozen pizza", 2.6);
cart.put("milk", 1.89);
cart.put("bananas", 0.39);
cart.put("hot dog", 0.79);
cart.put("relish", 0.49);
cart.put("frozen dinner", 1.5);
cart.put("cereal", 1.55);
cart.put("tuna fish", 0.49);
cart.put("coffee", 0.6);
cart.put("pasta", 0.5);
cart.put("strawberries", 1.99);
cart.put("apples", 0.99);
cart.put("sugar", 1.5);
cart.put("sugar", 0.98);
return purchasePrice();
}
public static void main(String [] args){
computeProfit(sellingPrice(),purchasePrice(),allOrders());
}
}
Your answer looks mostly right, there are just a few issues with your type naming (Integer should be int, Double should be double) and you use Map.Entry in one portion of the code and Entry later on. The code below fixes the issues in your computeProfit function and should solve your problem. Let me know if you have any questions!
public static double computeProfit(HashMap<String, double> sellingPrice, HashMap<String, double> inventory, ArrayList<HashMap<String, int>> orders) {
double profit = 0;
for (HashMap<String, int> order: Orders) {
for (Map.Entry<String, int> orderEntry: order.entrySet()) {
double purchasePrice = inventory.get(orderEntry.getKey());
double salePrice = sellingPrice.get(orderEntry.getKey());
int purchaseCount = orderEntry.getValue();
profit += ( salePrice - purchasePrice ) * purchaseCount;
}
}
return profit;
}

HashBasedTable Table<String,String,Double> HashMap<String,Double>

i have HashMap<String,Double>hm1 and guava table Table<String, String, Double> employeeYearsOfService
HashMap hm1
fatima |0.97
AT&T |0.96
Table employeeYearsOfService
Google={Bill Smith=1.75, Stacy Lerner=11.5},
Microsoft={Bill Smith=13.2,Stacy Lerner=3.5},
AT&T={Bill Smith=2.0, Stacy Lerner=1.4},
fatima={Bill Smith=1.0, Stacy Lerner=2.0}
Table reseults
fatima={Bill Smith=1.0, Stacy Lerner=2.0}
AT&T={Bill Smith=2.0, Stacy Lerner=1.4}
and i want this result by create a new table Table<String, String, Double> results = HashBasedTable.create() contains a row of employeeYearsOfService
who have a same key with HashMap hm1 (this is my question)
this picture for mor understand
My Code
Table guava
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
employeeYearsOfService.put("AT&T", "Stacy Lerner", 1.4);
employeeYearsOfService.put("Microsoft", "Stacy Lerner", 3.5);
employeeYearsOfService.put("Microsoft", "Bill Smith", 13.2);
employeeYearsOfService.put("Google", "Stacy Lerner", 11.5);
employeeYearsOfService.put("AT&T", "Bill Smith", 2.0);
employeeYearsOfService.put("Google", "Bill Smith", 1.75);
employeeYearsOfService.put("fatima", "Bill Smith", 1.0);
employeeYearsOfService.put("fatima", "Stacy Lerner", 2.0);
hashmap hm1
HashMap<String, Double> hm = new HashMap<String, Double>();
HashMap<String, Double> hm1 = new HashMap<String, Double>();
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() * operatCible.get(k);
sum2 += employee.getValue() * employee.getValue();
vect1 += operatCible.get(k) * operatCible.get(k);
Result = (sum / (sqrt(sum2) * sqrt(vect1)));
k++;
}
hm.put(key, Result);
k = 0;
sum = 0.0;
sum2 = 0.0;
vect1 = 0.0;
Result = 0.0;
}
System.out.println(hm);
Set<Entry<String, Double>> set = hm.entrySet();
List<Entry<String, Double>> list = new ArrayList<Entry<String, Double>>
(set);
Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
public int compare(Map.Entry<String, Double> o1,
Map.Entry<String, Double> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
System.out.println(list);
System.out.println("le K nn");
for (Entry<String, Double> entry : list.subList(0, 2)) {
hm1.put(entry.getKey(), entry.getValue());
}
loop for new Table
Table<String, String, Double> results = HashBasedTable.create();
System.out.println(hm1);
for (Entry<String, Double> entry : list) {
if(entry.getKey().equals(employeeYearsOfService.rowKeySet())){
results.put(employeeYearsOfService.row(entry.getKey())));
// how i do it
}
}
thank you very much
One way would consist of removing the elements you don't want from the table:
employeeYearsOfService.rowKeySet()
.removeIf(key -> !hm1.containsKey(key));
Here I'm using the Table.rowKeySet method to get the set of row keys from the table. This set is bounded to the original table, meaning that when an element is removed from this set, an entire row (with the same key) will be removed from the table. And this is what I'm doing with the Collection.removeIf method, whose predicate returns true if the key is not present in the hm1 map.

How to reverse a HashMap?

I need to reverse the order of what the below method returns. For example if it
returns:
1=ball, 2=save, 3=take 4=till
I want to reverse and return:
1=till, 2=take, 3=save, 4=ball
My method is:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map;
}
Please check if the below code I've written is useful for you as a reference:
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> iterator = keySet.descendingIterator();
Integer i;
while(iterator.hasNext())
{
i = iterator.next();
reverseMap.put(i,map.get(i));
}
System.out.println(reverseMap);
}
//map to arrange inizialized
LinkedHashMap<String,object> mta;
//transforms into arrayList hashmap keys and values
ArrayList<Object> valuesTMP=new ArrayList<Object>(mta.values());
ArrayList<String> keysTMP;
keysTMP=new ArrayList<String>(mta.keySet());
//reverse
Collections.reverse(valuesTMP);
Collections.reverse(keysTMP);
LinkedHashMap <String,Object> mtarranged=new LinkedHashMap<String, Object>();
int index=0;
for( String key : keysTMP){
mtarranged.put(key,valuesTMP.get(index));
index++;
}
To answer this question, we need to know how you're iterating the Map since Maps don't have entry order. However, you may try using a TreeMap which has the method descendingMap:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map.descendingMap();
}
Edit: From your comment, your intent is more clear. A TreeMap will help you with your goal because it is a Map ordered by the natural order of the keys.
I've made some changes to the code. Please check if this is OK for you now.
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> forwardIterator = keySet.iterator();
Iterator<Integer> reverseIterator = keySet.descendingIterator();
Integer i;
Integer j;
while(forwardIterator.hasNext())
{
i = forwardIterator.next();
j = reverseIterator.next();
reverseMap.put(i,map.get(j));
}
System.out.println(reverseMap);
}
Please find the below code and Let me know Which is suitable for you ...
int iterationValue = 0;
List<String> stringList = new LinkedList<String>();
stringList.add("ball");
stringList.add("save");
stringList.add("tick");
Map<Integer, String> map = new HashMap<Integer, String>();
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Input MAP
System.out.println(map); // {0=ball, 1=save, 2=tick}
Collections.reverse(stringList);
iterationValue = 0;
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Output MAP
System.out.println(map); // {0=tick, 1=save, 2=ball}

How to Get Values from List of HashMap?

I have a List of HashMap's which has key of type Integer and value of type Long.
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
ListofHash.add(mMap);
}
Now, how do I retrieve the key and value from the list of HashMap?
If using Collection class is the solution, please enlight me.
Update 1:
Actually i am getting the value from the database and putting that into a HashMap
public static List<Map<Integer, Long>> populateMyHashMapFromDB()
{
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(getIntFromDB(i)), Long.valueOf(getLongFromDB(i)));
ListofHash.add(mMap);
}
return ListofHash;
}
where getIntFromDB and getLongFromDB can retreive any int and long values respectively.
Now this is where i want to get my values that i got from DB both keys and values
public void getmyDataBaseValues()
{
List<HashMap<Integer,Long>> ListofHash=populateMyHashMapFromDB();
// This is where i got confused
}
ANSWER This is why Peter Lawrey suggested
public class HashMaps {
public static void main(String[] args) {
// TODO Auto-generated method stub
testPrintHashmapValues(putToHashMap());
testPrintHashmapValuesWithList(putToHashMapWithList());
}
public static Map<Integer, Long> putToHashMap() {
Map<Integer, Long> map = new LinkedHashMap<Integer, Long>();
for (int i = 0; i < 10; i++) {
map.put(Integer.valueOf(i), Long.valueOf(200000000000L + i));
}
return map;
}
public static void testPrintHashmapValues(Map<Integer, Long> map) {
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + " value: "
+ entry.getValue());
}
}
public static List<Map<Integer, Long>> putToHashMapWithList() {
List<Map<Integer, Long>> listOfHash = new ArrayList<Map<Integer, Long>>();
for (int i = 0; i < 10; i++) {
Map<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L + i));
listOfHash.add(mMap);
}
return listOfHash;
}
public static void testPrintHashmapValuesWithList(
List<Map<Integer, Long>> listOfHash) {
for (int i = 0; i < 10; i++) {
Map<Integer, Long> map = listOfHash.get(i);
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println(i + " hashMap");
System.out.println("key: " + entry.getKey() + " value: "
+ entry.getValue());
}
}
}
}
My Task is done even without creating a List.
Its still not clear to me why you want a list.
public static Map<Integer, Long> populateMyHashMapFromDB() {
Map<Integer, Long> map = new LinkedHashMap<Integer, Long>();
for (int i = 0; i < 10; i++)
map.put(getIntFromDB(i), getLongFromDB(i));
return map;
}
Map<Integer, Long> map = populateMyHashMapFromDB();
Long value = map.get(key);
This collection isn't designed to give you the key/values pairs easily. I fyou need to this functionality I would suggest using a different structure.
Assuming you have a some bad code you cannot change, you can do
List<Map<Integer, Long>> maps = new ArrayList<Map<Integer, Long>>();
Map<Integer, Long> all = new HashMap<Integer, Long>();
for(Map<Integer, Long> map: maps)
all.putAll(map);
for(Map.Entry<Integer, Long> entry: all.entrySet() {
// do something which each key/value.
}
In this example you don't need a List or a Map.
long[] longs = new long[10];
for (int i = 0; i < 10; i++)
longs[i] = i;
int key = 1;
int num = longs[key];
You iterate over the list to get the maps, and then iterate over their key set:
public static void main(String[] args) throws NoSuchAlgorithmException {
List<Map<Integer, Long>> ListofHash = new ArrayList<Map<Integer,Long>>();
for (int i = 0; i < 10; i++) {
Map<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L + i));
ListofHash.add(mMap);
}
for (Map<Integer, Long> map : ListofHash) {
for (Integer key : map.keySet()) {
System.out.println(map.get(key));
}
}
}
Note: I've also changed a little your code, using Map instead of HashMap when possible
Something of this effect:
public static Long getValue(Integer key)) {
for (HashMap<Integer, Long> entry : ListofHash) {
if (entry.containsKey(key)) {
return entry.get(key);
}
}
return null;
}
//Retrieve all key/value
for (HashMap<Integer, Long> entry : ListofHash) {
for (Integer key : entry.keySet()) {
System.out.println("Key : " + key + ", value: " + entry.get(key));
}
}
PS Untested.
I am assuming you are asking how to get it from ArrayList,
ListofHash.get(0).get(Object key);
Object key means whatever Integer key you want
Good Luck!
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
ListofHash.add(mMap);
}
You have a total of 10 Maps with only one element stored. And those Maps are stored in a List. You can retrieve those Maps and its elements doing this:
public void testPrintHashmapValues() {
List<HashMap<Integer, Long>> listOfHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
listOfHash.add(mMap);
}
for (int i = 0; i < 10; i++) {
Map<Integer, Long> map = listOfHash.get(i);
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println(i + " hashMap");
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
}
}
Also the variables should not start with uppercase (ListOfHash). Even though java won't complain it is a bad practice and difficult to read code like that because one might think it's a class name instead of a variable.

Categories

Resources