Related
I have a nested HashMap with String keys that contains either List, Map, or String values. I would like to flatten them like the below.
Here is the data:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Map<String, Object> dates = new HashMap<String, Object>() {{
put("1999", new HashMap<String, Object>() {{
put("3", Arrays.asList("23", "24", "25"));
put("4", Arrays.asList("1", "2", "3"));
}});
put("2001", new HashMap<String, Object>() {{
put("11", new HashMap<String, Object>() {{
put("7", Arrays.asList("23", "24", "25"));
put("9", Arrays.asList("1", "2", "3"));
}});
put("12", "45");
}});
}};
System.out.println(dates);
}
}
Map looks like:
{2001={11={7=[23, 24, 25], 9=[1, 2, 3]}, 12=45},
1999={3=[23, 24, 25], 4=[1, 2, 3]}}
The flattening of map should look like this:
{2001.11.7.1=23, 2001.11.7.2=24, 2001.11.7.3=25, 2001.11.9.1=1, 2001.11.9.2=2,
2001.11.9.3=3, 2001.12=45, 1999.3.1=23, 1999.3.2=24, 1999.3.3=25,
1999.4.1=1, 1999.4.2=2, 1999.4.3=3}
Note: the level of nested arrays or maps is unknown, it may go more than 2 levels.
You can use recursion to flatten the Map. Each time you encounter a Map, recurse by flattening that Map; when you encounter a List, iterate over it and add the index to the current key. A single value can be trivially set otherwise. See the below code in action here.
public static Map<String, Object> flatten(final Map<String, Object> map) {
return flatten("", map, new HashMap<>());
//use new TreeMap<>() to order map based on key
}
#SuppressWarnings("unchecked")//recursive helper method
private static Map<String, Object> flatten(final String key, final Map<String, Object> map,
final Map<String, Object> result) {
final Set<Map.Entry<String, Object>> entries = map.entrySet();
if (!entries.isEmpty()) {
for (final Map.Entry<String, Object> entry : entries) {
//iterate over entries
final String currKey = key + (key.isEmpty() ? "" : '.') + entry.getKey();
//append current key to previous key, adding a dot if the previous key was not an empty String
final Object value = entry.getValue();
if (value instanceof Map) {//current value is a Map
flatten(currKey, (Map<String, Object>) value, result);//flatten Map
} else if (value instanceof List) {//current value is a List
final List<Object> list = (List<Object>) value;
for (int i = 0, size = list.size(); i < size; i++) {
result.put(currKey + '.' + (i + 1), list.get(i));
}
//iterate over the List and append the index to the current key when setting value
} else {
result.put(currKey, value);//set normal value
}
}
}
return result;
}
public static void main(final String[] args){
final Map<String, Object> flattened = flatten(dates);
System.out.println(flattened);
}
You can iterate over this map, and process each entry value, depending on its instance of: Map, List, or String. Since the level of nested arrays or maps is unknown, I have modified a little your code example and flat map format for clarity, also I used TreeMap instead of HashMap for entries ordering.
public static void main(String[] args) {
TreeMap<String, Object> treeMap = new TreeMap<String, Object>() {{
put("1999", new TreeMap<String, Object>() {{
put("3", Arrays.asList("23", "24", "25"));
put("4", Arrays.asList("1", "2", new TreeMap<String, Object>() {{
put("10", "42");
}}));
}});
put("2001", new TreeMap<String, Object>() {{
put("11", new TreeMap<String, Object>() {{
put("7", Arrays.asList("23", "24", "25"));
put("9", Arrays.asList("1", "2", "3"));
}});
put("12", "45");
}});
}};
TreeMap<String, String> flatMap = new TreeMap<>();
processMap("", treeMap, flatMap);
System.out.println(treeMap);
System.out.println(flatMap);
}
private static void processMap(String prefix,
Map<String, Object> map,
Map<String, String> flatMap) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
processEntry(prefix, key, value, flatMap);
}
}
private static void processList(String prefix,
List<Object> list,
Map<String, String> flatMap) {
for (int i = 0; i < list.size(); i++) {
String key = String.valueOf(i + 1);
Object value = list.get(i);
processEntry(prefix, key, value, flatMap);
}
}
#SuppressWarnings("unchecked")
private static void processEntry(String prefix,
String key,
Object value,
Map<String, String> flatMap) {
if (value instanceof Map) {
processMap(prefix + key + ".", (Map<String, Object>) value, flatMap);
} else if (value instanceof List) {
processList(prefix + key + ":", (List<Object>) value, flatMap);
} else if (value instanceof String) {
flatMap.put(prefix + key, (String) value);
}
}
Sample map:
{1999={3=[23, 24, 25], 4=[1, 2, {10=42}]},
2001={11={7=[23, 24, 25], 9=[1, 2, 3]}, 12=45}}
Flattened map:
{1999.3:1=23, 1999.3:2=24, 1999.3:3=25, 1999.4:1=1, 1999.4:2=2, 1999.4:3.10=42,
2001.11.7:1=23, 2001.11.7:2=24, 2001.11.7:3=25,
2001.11.9:1=1, 2001.11.9:2=2, 2001.11.9:3=3, 2001.12=45}
Opposite: Restoring a value tree from its flat map representation.
private static Map<String, String> flatten(Map<String, Object> m) {
var pairs = new ArrayList<String[]>();
flatten(null, m, pairs);
return pairs.stream().collect(Collectors.toMap(x -> x[0], x -> x[1]));
}
private static void flatten(String prefix, Map<String, Object> m, List<String[]> pairs) {
for (var e : m.entrySet()) {
var k = e.getKey();
var o = m.get(k);
if (o instanceof String s) {
pairs.add(new String[]{makeKey(prefix, k), s});
} else if (o instanceof List l) {
IntStream.range(0, l.size())
.mapToObj(i -> new String[]{
makeKey(prefix, k + "." + (i +1)),
l.get(i).toString()
})
.forEach(p -> pairs.add(p));
} else if (o instanceof Map nestedMap) {
flatten(makeKey(prefix, k), nestedMap, pairs);
}
}
}
private static String makeKey(String prefix, String key) {
return String.join(".", prefix == null ? List.of(key) : List.of(prefix,key));
}
I went through all the manuals out there and all SO questions but still unable to figure this out...
I have a List (integer represents age):
List<Person> people = Arrays.asList
(
new Person("bob", 10),
new Person("sue", 4),
new Person("tom", 37),
new Person("jim", 10),
new Person("boo", 4),
new Person("ekk", 53),
new Person("joe", 10)
);
I need to:
group the list by age,
sort by group sizes (descending),
sort by age (descending)
So using the example above the result would have to be like this:
{10=[bob, jim, joe],4=[sue, boo], 53=[ekk], 37=[tom]}
What I tried:
I tried with and without streams. I failed on both.
Note: I would lean toward no stream solution, because from my testing of the below code it seems like streams are much slower (I used System.nanotime()). These 3 operations will be done thousands of times each time, so it may make a slight difference.
Using streams here is what I did:
List<List<Person>> grpd = new ArrayList<>
(
people.stream()
.collect
(
groupingBy(Person::getAge, toList())
)
.values()
);
grpd = grpd.stream().sorted((a, b) -> Integer.compare(b.size(), a.size())).collect(toList());
No streams approach:
Map<Integer, List<Person>> grouped = new HashMap<>();
for (Person person : people)
{
if (grouped.containsKey(person._age))
{
grouped.get(person._age).add(person);
} else
{
List<Person> p = new ArrayList<>();
p.add(person);
grouped.put(person._age, p);
}
}
List<Map.Entry<Integer, List<Person>>> entries = new ArrayList<>(grouped.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<Integer, List<Person>>>()
{
#Override
public int compare(Map.Entry<Integer, List<Person>> o1, Map.Entry<Integer, List<Person>> o2)
{
return Integer.compare(o2.getValue().size(), o1.getValue().size());
}
});
Map<Integer, List<Person>> sortedBySize = new LinkedHashMap<>();
for (Map.Entry<Integer, List<Person>> entry : entries)
{
sortedBySize.put(entry.getKey(), entry.getValue());
}
Problem:
I have no idea how to add the final sort on either case.
public class Person
{
public String _name;
public int _age;
public int getAge() { return _age; }
public Person(String name, int age)
{
_name = name;
_age = age;
}
#Override
public String toString()
{
return _name;
}
}
Use streams.
First, group them by age:
Map<Integer, List<Person>> groupedByAge =
people.stream().collect(groupingBy(Person::getAge));
Then sort the entries of this map:
Comparator<Map.Entry<Integer, List<Person>>> byCount = comparingInt(e -> e.getValue().size());
Comparator<Map.Entry<Integer, List<Person>>> byAge = comparingInt(Map.Entry::getKey);
Stream<Map.Entry<Integer, List<Person>>> sorted =
groupedByAge.entrySet().stream().sorted(byCount.reversed().thenComparing(byAge.reversed()));
Then just get the list out of there:
List<List<Person>> result = sorted.map(Map.Entry::getValue).collect(toList());
(You can put this all into a single expression, but I claim it is more readable broken out like this).
As you've also asked about a non-stream solution, here it is:
Map<Integer, List<Person>> grouped = new HashMap<>();
people.forEach(person -> grouped.computeIfAbsent(
person.getAge(),
k -> new ArrayList<>())
.add(person));
This groups by age. Now let's sort the entries, first by group size descending, then by age descending:
List<Map.Entry<Integer, List<Person>>> toSort = new ArrayList<>(grouped.entrySet());
toSort.sort(
Comparator.comparingInt((Map.Entry<Integer, List<Person>> e) -> e.getValue().size())
.reversed()
.thenComparingInt(Map.Entry.comparingByKey().reversed()));
Now, toSort is a sorted list of entries. You need to put those entries into a new map:
Map<Integer, List<Person>> sorted = new LinkedHashMap<>();
toSort.forEach(e -> sorted.put(e.getKey(), e.getValue()));
And sorted holds the result you want.
Since you were also looking for a non-stream solution:
public static Map<Integer, List<Person>> group(List<Person> people) {
Map<Integer, List<Person>> intermediateGrouping = new HashMap<>();
for (Person person : people) {
intermediateGrouping.computeIfAbsent(person.getAge(), k -> new ArrayList<>()).add(person);
}
Comparator<Entry<Integer, List<Person>>> byGroupSize = Entry.comparingByValue(Comparator.comparingInt(List::size));
Comparator<Entry<Integer, List<Person>>> byAge = Entry.comparingByKey();
List<Entry<Integer, List<Person>>> entries = new ArrayList<>(intermediateGrouping.entrySet());
entries.sort(byGroupSize.reversed().thenComparing(byAge.reversed()));
Map<Integer, List<Person>> result = new LinkedHashMap<>(entries.size());
for (Entry<Integer, List<Person>> entry : entries) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
Or if you prefer the result to be a List<List<Person>>:
public static List<List<Person>> group(List<Person> people) {
Map<Integer, List<Person>> intermediateGrouping = new HashMap<>();
for (Person person : people) {
intermediateGrouping.computeIfAbsent(person.getAge(), k -> new ArrayList<>()).add(person);
}
Comparator<Entry<Integer, List<Person>>> byGroupSize = Entry.comparingByValue(Comparator.comparingInt(List::size));
Comparator<Entry<Integer, List<Person>>> byAge = Entry.comparingByKey();
List<Entry<Integer, List<Person>>> entries = new ArrayList<>(intermediateGrouping.entrySet());
entries.sort(byGroupSize.reversed().thenComparing(byAge.reversed()));
List<List<Person>> result = new ArrayList<>(entries.size());
for (Entry<Integer, List<Person>> entry : entries) {
result.add(entry.getValue());
}
return result;
}
Try modifiying your sort comparator using the below implementation when the sizes are equal for a no streams approach
Collections.sort(entries, new Comparator<Map.Entry<Integer, List<Person>>>()
{
#Override
public int compare(Map.Entry<Integer, List<Person>> o1, Map.Entry<Integer, List<Person>> o2)
{
if(o1.getValue().size()<o2.getValue().size())
return 1;
else if(o1.getValue().size()>o2.getValue().size())
return -1;
else {
if( o1.getKey()< o2.getKey())
return 1;
else if(o1.getKey()>o2.getKey())
return -1;
else
return 0;
}
}
});
Let me know if it works on all your Test Cases
I have a few methods that I was given from here a few days ago to help me with my scores. Basically when the game ends I want to get the top players with the best scores and put them into round 2, so if there were 8 players I want it to split them in half and the top half being the ones with the best scores, the methods below work fine but if there were 3 players in the game it would only take the top one instead of 2, 5 players in the game it would only take the top 2 instead of 3.
How do I get the top half with the highest scores and if say 2 players have the same score, then both of them would go through. For example:
Player 1 = 1;
Player 2 = 10;
Player 3 = 10;
Player 4 = 25;
Methods below would return player 4 and 3 but player 2 also has 10 points so he should be in it too.
public static Map<String, Integer> getTopHalf(Map<String, Integer> map){
Map<String, Integer> sorted = sortByComparator(map);
Map<String, Integer> out = new HashMap<String, Integer>();
Iterator<Entry<String,Integer>> it = sorted.entrySet().iterator();
for(int i = 0; i<map.size()/2; i++){
Entry<String, Integer> e = it.next();
out.put(e.getKey(), e.getValue());
}
return out;
}
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap){
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>(){
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2){
return o2.getValue().compareTo(o1.getValue());
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void printMap(Map<String, Integer> map){
for (Entry<String, Integer> entry : map.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
And for testing I use this:
Map<String, Integer> unsortMap = new HashMap<String, Integer>();
unsortMap.put("B", 89);
unsortMap.put("A", 45);
unsortMap.put("f", 43);
unsortMap.put("j", 47);
unsortMap.put("h", 41);
System.out.println("After sorting descindeng order and deleting half......");
Map<String, Integer> half = getTopHalf(unsortMap);
printMap(half);
List<Integer> achievedPoints = new ArrayList<>(allPlayers.values());
Collections.sort(achievedPoints); /*- from few points to many points */
int requiredScore = achievedPoints.get(achievedPoints.size());
Map<String, Integer> playersInNextRound = new HashMap<>();
for (Map.Entry<String, Integer> player : allPlayers.entrySet()) {
if (player.getValue() >= requiredScore) {
playersInNextRound.put(player.getKey(), player.getValue());
}
}
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?
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.