Java How to get the index of a Map of HashMap [duplicate] - java

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 7 years ago.
Forgive me if it seems simple but I couldn't figure it out easily. I thought about using a loop but was wondering if anybody knows an easier way: I have:
Map<String, Integer> map = new HashMap<>();
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubD", 2);
map.put("ClubE", 3);
map.put("ClubF", 2);
map.put("ClubG", 2);
I need to get keys or values at specific index in my tests. For example I need to get the key and value at index 3 etc. The reason is that I use a comparator and sort the Map and would like to show that the value at a specific index has changed.
Thanks for any ideas.
UPDATE:
I used:
HashMap leagueTable = new HashMap();
Map<String, Integer> map = sortByValues(leagueTable);
public <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) {
return k1.compareTo(k2); // <- To sort alphabetically
} else {
return compare;
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
I then used aloop to print out values:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println( entry.getKey() + ", " + entry.getValue() );
}

Ended up using a for loop and comparing with what I already had added to the Map:
HashMap<String, Integer> map = new HashMap<>();
map.put("ClubD", 3);
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubE", 2);
map.put("ClubF", 2);
map.put("ClubG", 2);
Map<String, Integer> mapResult = instance.sortByValues(map);
String expectedResultKey = "ClubB";
int expectedResultValue = 1;
String resultKey = "";
int resultValue = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
resultKey = entry.getKey();
resultValue = entry.getValue();
}
assertSame(expectedResultKey, resultKey);

HashMap's don't have indices. They just store data in key-value pairs.
Instead of map being a Map, why don't you use a 2D array? (And give it a more appropriate name)
String[][] array = new String[3][3];
array[3] = new String[] { "ClubD" };
array[1] = new String[] { "ClubB" };
array[2] = new String[] { "ClubA", "ClubC", "ClubE", "ClubF", "ClubG" };
System.out.println(array[3][0]);
and then if you wanted to loop through that array, you would just do:
for (int a = 0; a < array.length; a++)
for (int b = 0; b < array[a].length; b++)
if (array[a][b] != null)
System.out.println("array["+a+"]["+b+"] is: "+array[a][b]);

Related

Determine frequency of duplicate values from two Hashmaps

I have created 2 HashMaps that store string values from two txt files. I am able to successfully print which values are duplicated amongst both Maps, however, I am having trouble determining how many times each values are duplicated.
Here is my code to identify duplicate values:
// find if hashmaps contain duplicate values
boolean val = wordsMap.keySet().containsAll(wordsMap1.keySet());
// create new entry for hashmap
for (Entry<String, Integer> str : wordsMap.entrySet()) {
System.out.println("================= " + str.getKey());
if(wordsMap1.containsKey(str.getKey())){
System.out.println("Map2 Contains Map 1 Key");
}
}
System.out.println("================= " + val);
Any suggestions? Thank you
I am thinking of something along the lines of
Map.values().equals(Map1.values()){
count++;
}
If I understand correctly, you want to find values which are common to two map objects. (Add null and/or other checks as required)
public static int duplicateCount(Map<String, Integer> m1, Map<String, Integer> m2) {
int count = 0;
Collection<Integer> m1Values = m1.values();
Collection<Integer> m2Values = m2.values();
for (Integer i : m1Values) {
if (m2Values.contains(i)) {
count++;
}
}
return count;
}
Here's a sample program have written based on my understanding of your doubt. It finds and displays the duplicate keys and also the duplicate values along with their frequencies of repetition. The logic is: To find the frequency, pass the duplicate element from map1 and the map2 as a parameter to countFrequency() method, which in turn will return the count of repetition.
package com.rahul.stackoverflow;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class DuplicateValHashMap {
public static void main(String[] args) {
Map<String, Integer> map1 = new HashMap<String, Integer>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
map1.put("A", 1);
map1.put("B", 2);
map1.put("C", 3);
map1.put("D", 4);
map1.put("E", 5);
map2.put("A", 1);
map2.put("F", 2);
map2.put("G", 1);
map2.put("H", 3);
map2.put("B", 2);
for(Entry<String, Integer> entrySet : map1.entrySet()){
if(map2.containsKey(entrySet.getKey())){
System.out.println("Map2 contains keys of map1.");
System.out.println("Duplicate keys are : " + entrySet.getKey());
}
if(map2.containsValue(entrySet.getValue())){
System.out.println("Map2 contains values of map1.");
System.out.println("Duplicate values are : " + entrySet.getValue()+
" which is repeated " + countFrequency(map2, entrySet.getValue())+ " times.");
}
}
}
public static int countFrequency(Map<String, Integer> map, Integer value){
int count = 0;
for(Entry<String, Integer> entrySet : map.entrySet()){
if(value == entrySet.getValue()){
count++;
}
}
return count;
}
}
To get the number of duplicate keys between Maps,
public static int getDuplicateKeyCount(Map<?, ?> m1, Map<?, ?> m2) {
Set<?> tempSet = new HashSet<>(m1.keySet());
tempSet.retainAll(new ArrayList<>(m2.keySet()));
return tempSet.size();
}
To get the number of duplicate values between Maps,
public static int getDuplicateValueCount(Map<?, ?> m1, Map<?, ?> m2) {
List<?> tempList = new ArrayList<>(m1.values());
tempList.retainAll(m2.values());
return tempList.size();
}
To get a Map containing the frequency of the values of m1 in m2
public static <K, V> Map<V, Integer> getValueFrequencyMap(Map<K, V> m1, Map<K, V> m2) {
Map<V, Integer> freq = new HashMap<>();
Collection<V> col = m2.values();
for(V val : m1.values()) {
freq.put(val, Collections.frequency(col, val));
}
return freq;
}

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 discover which value occurs the most in a HashMap?

Map<String,String> votes = new HashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
How can I retrieve the value that most a occur in the HashMap above, in this case that would be "School". I would appreciate the most efficient and clear method to approach.
A simpler solution is to just look at the values.
public static <E> E mostFrequentElement(Iterable<E> iterable) {
Map<E, Integer> freqMap = new HashMap<>();
E mostFreq = null;
int mostFreqCount = -1;
for (E e : iterable) {
Integer count = freqMap.get(e);
freqMap.put(e, count = (count == null ? 1 : count+1));
// maintain the most frequent in a single pass.
if (count > mostFreqCount) {
mostFreq = e;
mostFreqCount = count;
}
}
return mostFreq;
}
and for a Map you can do
V v = mostFrequentElement(map.values());
One solution would be:
Construct a new HashMap that has a String key and an int value.
For each value of your current HashMap:
Add the value as the key in the new HashMap and the value as 1 if it's the first time you're inserting it.
Otherwise, increment the value by one for the current key.
Now iterate on the newly created map and retrieve the key that has the maximum value.
For your current map:
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
You'll first insert School as a key, with value 1. Then you face School again, so you increment the value by 1, having a count of 2. Now you insert Work with value 1, and Party with value 1 as well.
After iterating on the map, you'll get School with the highest value. And that's what you want!
Just using the API :
Map<String,String> votes = new HashMap<String,String>();
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
Collection<String> c = votes.values();
List<String> l = new ArrayList<>(c);
Set<String> set = new HashSet<>(c);
Iterator<String> i = set.iterator();
String valueMax = "";
int max = 0;
while(i.hasNext()){
String s = i.next();
int frequence = Collections.frequency(l, s);
if(frequence > max){
max = frequence;
valueMax = s;
}
}
System.out.println(valueMax+": "+max);
Output :
School: 2
Here is the implementation of Maroun pseudocode. Try,
Map<String, String> votes = new HashMap<String, String>();
votes.put("Henk", "School");
votes.put("Elise", "School");
votes.put("Jan", "Work");
votes.put("Mert", "Party");
//Define a countMap with String as value, Integer for count
Map<String, Integer> countMap = new HashMap<>();
for (Map.Entry<String, String> entry : votes.entrySet()) {
if (countMap.containsKey(entry.getValue())) {
countMap.put(entry.getValue(), countMap.get(entry.getValue()) + 1);
} else {
countMap.put(entry.getValue(), 1);
}
}
// Got the number of maximum occuarance
Integer maxNum = Collections.max(countMap.values());
String result = "";
// Iterate to search the result.
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
if(maxNum==entry.getValue()){
result=entry.getKey();
}
}
System.out.println(result);
I believe this will do what you want -
/**
* Get the most frequent value present in a map.
*
* #param map
* The map to search.
* #return The most frequent value in the map (or null).
*/
public static <K, V> V getMostFrequentValue(
Map<K, V> map) {
// Make sure we have an entry.
if (map != null && map.size() > 0) {
// the entryset from our input.
Set<Entry<K, V>> entries = map.entrySet();
// we need a map to hold the count.
Map<V, Integer> countMap = new HashMap<V, Integer>();
// iterate the entries.
for (Entry<K, V> entry : entries) {
// get the value.
V value = entry.getValue();
if (countMap.containsKey(value)) {
// if we've seen it before increment the previous
// value.
countMap.put(value, countMap.get(value) + 1);
} else {
// otherwise, store 1.
countMap.put(value, 1);
}
}
// A holder for the maximum.
V maxV = null;
for (Entry<V, Integer> count : countMap.entrySet()) {
if (maxV == null) {
maxV = count.getKey();
continue;
}
if (count.getValue() > countMap.get(maxV)) {
maxV = count.getKey();
}
}
return maxV;
}
return null;
}
You could override the put() and remove() of the HashMap class and create your custom one that also controls for the number of objects added. Like so:
public class MyHashMap<K, V> extends HashMap<K, V> {
private HashMap<String, Integer> countMap = new HashMap<String, Integer>();
#Override
public V put(K key, V value) {
Integer count = countMap.get(value);
if (count != null) {
countMap.put((String) value, ++count);
} else {
countMap.put((String) value, new Integer(1));
}
return super.put(key, value);
}
#Override
public V remove(Object key) {
String countKey = (String) get(key);
Integer count = countMap.get(countKey);
if (count != null) {
countMap.put(countKey, --count);
}
return super.remove(key);
}
public Integer getCount(Object value) {
return countMap.get((String)value);
}
}
This way you don't have to loop over the elements of your HashMap to count them. Instead, after you add them:
Map<String,String> votes = new MyHashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
You could just get the count for each as:
Integer schoolCount = votes.getCount("School");

Sorting by values in HashMap class using Java

I'm trying to get results HashMap sorted by value.
This is HashMap's keys and values:
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
I try to get results like this:
1 = can
2 = selin
4 = burak
5 = ertu
Here is my code:
import java.util.*;
public class mapTers {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext()) {
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++) {
while (t.hasNext()) {
if (dizi[i].equals(map.get(t.next()))) {
System.out.println(dizi[i] + " = " + t.next());
}
}
}
}
}
You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.
Here's my solution:
import java.util.*;
public class mapTers
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext())
{
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++)
{
t = anahtarlar.iterator();
while (t.hasNext())
{
String temp = (String)t.next();
if (dizi[i].equals(map.get(temp)))
{
System.out.println(dizi[i] + " = " + temp);
}
}
}
}
}
You cannot do that from a Map. At least not directly.
Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.
Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.
This is one of the solutions take from: https://stackoverflow.com/a/13913206/1256583
Just pass in the unsorted map, and you'll get the sorted one.
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
}
else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
To print, do a simple iteration over the entry set:
public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
You probably have the wrong data structure for this problem. Either:
Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
Use a bidirectional map as provided by libraries like Google Guava.
Reversed Map
private final SortedMap<Integer, String> TRANSLATIONS;
static {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "can");
// ...
TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}
Guava BiMap
private final BiMap TRANSLATIONS =
new ImmutableBiMap.Builder<String, Integer>()
.put("ertu", 5);
.put("burak", 4);
.put("selin", 2);
.put("can", 1);
.build();
Then, iterate over a sorted version of the key set or value set as needed. For example,
TRANSLATIONS.inverse.get(4); // "burak"
I'm just curious. What language are your strings in?

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