How to iterate a map from another map? - java

I have this Map where the key is an Integer and the value is another map. I want to know how to iterate through the second map.
private Map<Integer,Map<Integer,Integer>> transition = new HashMap<Integer, Map<Integer, Integer>>();

private Map<Integer,Map<Integer,Integer>> transition = new HashMap<Integer, Map<Integer, Integer>>();
for (Integer outerKey : transition.keySet()) {
Map<Integer, Integer> inner = transition.get(outerKey);
for (Integer innerKey : inner.keySet()) {
Integer value = inner.get(innerKey);
}
}

+1 #angel_navarro Another way is using entry set
Map<Integer, HashMap<Integer, Integer>> map = new HashMap<Integer, HashMap<Integer, Integer>>();
for (Map.Entry<Integer, HashMap<Integer, Integer>> entry : map.entrySet()) {
HashMap<Integer, Integer> submap = entry.getValue();
for (Map.Entry<Integer, Integer> sub_entry : submap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
}
}

I like this idiom better:
for(Map.Entry<Integer,Map<Integer,Integer>> outer : transition.entrySet()){
Integer outerKey = outer.getKey();
for(Map.Entry<Integer,Integer> inner : outer.getValue().entrySet()){
Integer innerKey = inner.getKey();
Integer innerValue = inner.getValue();
}
}
By the way, I suggest you take a look at Guava's new collection types, e.g., Multimap, for alternatives to nested collections. Maybe they won't fit your use case today, but it's good to know they exist.

private Map<Integer,Map<Integer,Integer>> transition = new HashMap<Integer, Map<Integer, Integer>>();
for(Map.Entry<Integer,Map<Integer,Integer>> entryMap : transition.values())
{
final Integer outerKey = entryMap.getKey();
for (Map.Entry<Integer, Integer> entry : entryMap.getValue().entrySet())
{
final Integer innerKey = entry.getKey();
final Integer innerValue = entry.getValue();
}
}

Related

looping through iterator returns the same value

I have the issue that my loop does not break and returns the same value
public Map<String, String> getKeysByValue(Map<String, Map<String, Peple>> map, Collection<Peple> value) {
Map<String, String> stringStringMap = new HashMap<>();
int count = 0;
while (value.iterator().hasNext()) {
for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
String verified = value.iterator().next().gerVerfied();
if (verified.equals("true")) {
stringStringMap.put(entry1.getKey(), value.iterator().next().getName());
}
}
}
The problem here is that the same value kets put in the map for every key (value.iterator().next().getName()) always returns the same string
I think the below would be a correct approach for your problem:
public Map<String, String> getKeysByValue(Map<String, Map<String, Peple>> map, Collection<Peple> value) {
Map<String, String> stringStringMap = new HashMap<>();
int count = 0;
Iterator<People> peopleIterator = value.iterator();
while (peopleIterator.hasNext()) {
for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
People people = peopleIterator.next();
String verified = people.gerVerfied();
if (verified.equals("true")) {
stringStringMap.put(entry1.getKey(), people.getName());
}
}
}
You need to store the iterator in a variable.
Consider below simple code :
Collection<String> strings = new ArrayList<>();
strings.add("value1");
strings.add("value2");
strings.add("value3");
strings.add("value4");
while (strings.iterator.hasNext())
{
System.out.println(strings.iterator.next());
}
This will run infinitely and will only print value1, but if you modify the code as below :
Collection<String> strings = new ArrayList<>();
strings.add("value1");
strings.add("value2");
strings.add("value3");
strings.add("value4");
Iterator<String> stringIterator = strings.iterator();
while (stringIterator.hasNext())
{
System.out.println(stringIterator.next());
}
It runs smooth.
You can learn more about iterator here : https://www.geeksforgeeks.org/how-to-use-iterator-in-java/
ALso, I think as you are calling iterator twice without checking hasNext() on the second call, it can throw java.util.NoSuchElementException
You are calling next() twice on that iterator. That moves it ahead and picks up the name of the next People, which might not be verified.
I believe you just want to get the name if it's a verified Peple?
while (value.iterator().hasNext()) {
for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
Peple nextPeple = value.iterator().next();
String verified = nextPeple.gerVerfied();
if (verified.equals("true")) {
stringStringMap.put(entry1.getKey(), nextPeple.getName());
}
}
}
}
Every time you call value.iterator() new Iterator object is created from scratch, pointing to a first element. To avoid it, store first result of calling it into local variable.
Iterator<Peple> it = value.iterator();
while(it.hasNext()){
// your remaiing code
}
This code works fine with the below input:
import java.util.*;
public class Test {
public static void main(String[] ar){
Map<String, People> entry1 = new HashMap<String , People>();
People people1 = new People("true","name1");
People people2 = new People("false","name2");
People people3 = new People("true","name3");
entry1.put("user1", people1);
entry1.put("user2", people2);
entry1.put("user3", people3);
Map<String, People> entry2 = new HashMap<String , People>();
People people4 = new People("true","name1");
People people5 = new People("false","name2");
People people6 = new People("true","name3");
entry2.put("user1", people4);
entry2.put("user2", people5);
entry2.put("user3", people6);
Map<String, Map<String, People>> map2 = new HashMap<String, Map<String,
People>>();
map2.put("set1",entry1);
map2.put("set2",entry2);
Collection<People> strings = new ArrayList<>();
strings.add(people1);
strings.add(people6);
strings.add(people5);
strings.add(people3);
strings.add(people2);
getKeysByValue(map2, strings);
}
public static Map<String, String> getKeysByValue(Map<String, Map<String, People>> map, Collection<People> value) {
Map<String, String> stringStringMap = new HashMap<>();
int count = 0;
Iterator<People> it = value.iterator();
while (it.hasNext()) {
People people = it.next();
for (Map.Entry<String, Map<String, People>> entry : map.entrySet()) {
for (Map.Entry<String, People> entry1 : entry.getValue().entrySet()) {
String verified = people.getVerified();
System.out.println(verified);
System.out.println("Key : "+entry1.getKey() +" Value : "+entry1.getValue().getVerified());
if (verified.equals(entry1.getValue().getVerified())) {
stringStringMap.put(entry1.getKey(), people.getName());
}
}
}
}
System.out.println(stringStringMap);
return stringStringMap;
}
}
People.java
public class People {
String verified;
public People(String verified, String name){
this.verified = verified;
this.name = name;
}
public String getVerified() {
return verified;
}
public String getName() {
return name;
}
String name;
}
Try this:
public Map<String, String> getKeysByValue(Map<String, Map<String, Peple>> map, Collection<Peple> value) {
Map<String, String> stringStringMap = new HashMap<>();
int count = 0;
Iterator<Peple> iterator = value.iterator();
while (iterator.hasNext()) {
Peple p = iterator.next();
for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
String verified = p.gerVerfied();
if (verified.equals("true")) {
stringStringMap.put(entry1.getKey(), p.getName());
}
}
}
}
}

Want to concatenate Value of one map to key of another map

I want to concatenate to the value of one map to key of another map and add them into list.
Compare value on basis of key of first map to value of another map.
e.g:
map1= {37=core__error_code_based, 153=core__app_dialog, 123=core__date}
map2={copy_2=37,button_back=37,button_cancel=153,button_confirm=153}
My approach is in first loop i get the key of map1 and then in second loop iterate the map2 values on basis map1 key.
So that I get the value of map1 and key of map2 and later concatenate in string.
List<String> finalKey=new ArrayList<>();
Iterator<Map.Entry<String,String>> entrySet=map1.entrySet().iterator();
Iterator<Map.Entry<String,String>> pageKey=map2.entrySet().iterator();
while(entrySet.hasNext()){
Map.Entry<String,String> entry = entrySet.next();
Map.Entry<String,String> pageValue = pageKey.next();
while(entry.getKey()==pageValue.getValue()){
finalKey.add(entry.getValue()+"__"+pageValue.getKey());
}
}
I had tried using iterator and entryset to iterate through the both map but not succeed
{core__error_code_based__copy_2,core__error_code_based__button_back,core__app_dialog__button_confirm,core__app_dialog__button_cancel}
Well i achieved this using
public class translatekeyName {
static List<String> finalString = new ArrayList<>();
public static Map<String, String> initialMap() {
Map<String, String> map1 = new HashMap<>();
map1.put("37", "core__error_code_based");
map1.put("153", "core__app_dialog");
return map1;
}
public static Map<String, String> secondMap() {
Map<String, String> map2 = new HashMap<>();
map2.put("copy_2", "37");
map2.put("button_back", "37");
map2.put("button_cancel", "153");
map2.put("button_confirm", "153");
return map2;
}
public List<String> concatenateString(Map page, Map source) {
Map<String, String> moduleKey = page;
Map<String, String> pageKey = source;
List<String> temp;
Iterator<Map.Entry<String, String>> entrySet = page.entrySet().iterator();
Iterator<Map.Entry<String, String>> pageKeyset = source.entrySet().iterator();
for (String value : moduleKey.keySet()) {
temp = getallKeys(source, value);
String tempValue = moduleKey.get(value);
for (int i = 0; i < temp.size(); i++) {
tempValue += "__" + temp.get(i);
finalString.add(tempValue);
}
}
return finalString;
}
static <K, V> List<K> getallKeys(Map<K, V> mapOfWords, V value) {
List<K> keylist = null;
if (mapOfWords.containsValue(value)) {
keylist = new ArrayList<>();
for (Map.Entry<K, V> entry : mapOfWords.entrySet()) {
if (entry.getValue().equals(value)) {
keylist.add(entry.getKey());
}
}
}
return keylist;
}
public static void main(String[] args) {
translatekeyName obj = new translatekeyName();
obj.concatenateString(initialMap(), secondMap());
System.out.println(finalString);
}
}

How to "print" a HashMap in a Hashmap in Java/Android

I want to "print" a Hashmap<String, Integer> (let's say Alpha) in a Hashmap<String, Hashmap<String, Integer>> (Beta) and I say "print" because I don't want the "printed" Alpha to change when I re-use Alpha.
For example:
class scratch_2 {
public static void main(String[] args) {
HashMap<String, Integer> Alpha = new HashMap<>();
HashMap<String, HashMap<String, Integer>> Beta = new HashMap<>();
Beta.put("A1", Alpha);
Beta.put("B2", Alpha);
Alpha.put("A", 1);
Alpha.put("B", 2);
System.out.println(Beta); --->print1
Alpha.clear();
System.out.println(Beta); ---->print2
}
}
Result of print1: {A1={A=1, B=2}, B2={A=1, B=2}}
Result of print2: {A1={}, B2={}}
How to set the Beta.put() so that when Alpha is cleared, Beta remains the same?
Here is what you can do to reset a nested HashMap. The value is removed on line 22 and then added back as a new inner hashmap instance. Again, I loop through containingMap and the innerMap getting each map. Once I have a value to reset I call the reset function.
import java.util.*;
import java.lang.*;
public class Collections {
public HashMap<String, HashMap<String, Integer>>
createMap(String beta, String alpha, int m, HashMap<String,
Integer> innerStructure, HashMap<String, HashMap<String,
Integer>> containingStructure) {
while(m>0) {
innerStructure.put(beta, m);
m--;
}
containingStructure.put(alpha, innerStructure);
return containingStructure;
}
public void reset(HashMap<String, HashMap<String, Integer>>
map, int x) {
HashMap<String, Integer> betaMap = new HashMap<String, Integer>();
for(Map.Entry<String,HashMap<String,Integer>> entry: map.entrySet()) {
System.out.println("Key before is:" + entry.getKey());
if(entry.getValue() instanceof Map) {
for(Map.Entry<String, Integer> mapEntry: entry.getValue().entrySet()) {
if(mapEntry.getValue() == x) {
entry.getValue().remove(x);
map.put(entry.getKey(), betaMap);
}
}
}
}
}
public void print(HashMap<String, HashMap<String, Integer>> map) {
for(Map.Entry<String,HashMap<String,Integer>> entry: map.entrySet()) {
System.out.println("Key is:" + entry.getKey());
if(entry.getValue() instanceof Map) {
for(Map.Entry<String, Integer> mapEntry: entry.getValue().entrySet()) {
System.out.println(mapEntry.getKey());
}
}
}
}
public static void main(String[] args) {
Collections collections = new Collections();
HashMap<String, Integer> innerStructure = new HashMap<>();
HashMap<String, HashMap<String, Integer>> containingStructure = new HashMap<>();
containingStructure = collections.createMap("B1", "A1", 4, innerStructure, containingStructure);
collections.reset(containingStructure, 2);
collections.print(containingStructure);
}
}
It really doesn't change the Beta with put it is a matter of evaluating each entry and making sure it is a new HashMap type being used in it's place. I think this should help.
As #Andreas said, I should have created a new instance of Alpha by assigning it like Alpha = new HashMap<>(); when I no longer needed it. I can then re-use it without affecting Beta.

A hashmap inside of a hasmap print out

I am trying to print out a hashmap that contains A character as the key and the value as another hashmap with Integer and Double
I have this so far but isn't working.
HashMap<Character, Map<Integer, Double>> MapInsideOfAMap = calc.MapInAMap(abc);
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Char: " + outer.getKey() + "\n");
for (Map.Entry<Character, Map<Integer, Double> inner : MapInsideOfAMap.getValue().entrySet()) {
System.out.println("int = " + inner.getKey() + ", double = " + inner.getValue());
}
}
Your code should be like this,
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Char: " + outer.getKey() + "\n");
for (Entry<Integer, Double> inner : MapInsideOfAMap.get(outer.getKey()).entrySet()) {
System.out.println("int = " + inner.getKey() + ", double = " + inner.getValue());
}
}
Okay, I understood what you were trying to do,
since you already got Outer map entry, you don't have to again use outer map reference, you can directly do like this,
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Char: " + outer.getKey() + "\n");
for (Entry<Integer, Double> inner : outer.getValue().entrySet()) {
System.out.println("int = " + inner.getKey() + ", double = " + inner.getValue());
}
}
Let's assume your map looks like this:
Map <Character, Map<Integer, Double>> MapInsideOfAMap = new HashMap();
then you can print your map like this:
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Char: " + outer.getKey() + "\n");
HashMap<Integer, Double> innermap = MapInsideOfAMap.get(outer.getKey());
for (Map.Entry<Integer, Double> innerEntry : innermap.entrySet()) {
System.out.println("int = " + innerEntry.getKey() + ", double = " + innerEntry.getValue());
}
}
If you need just to see map key/values, use System.out.println
Map AbstractMap.toString knows how to print itself in a nice and readable way.
Map<Character, Map<Integer, Double>> map = new HashMap<>();
map.put('A', new HashMap<>());
map.get('A').put(1, 0.01);
map.put('B', new HashMap<>());
map.get('B').put(2, 0.02);
System.out.println(map);
prints out this :
{A={1=0.01}, B={2=0.02}}
To simply print out the whole map of maps:
System.out.println(mapInsideOfAMap);
Now, if you want to iterate your outer and inner maps and print their key/value pairs you could use the Map.forEach method:
mapInsideOfAMap.forEach((outerKey, outerValue) -> {
System.out.println("Char: " + outerKey + "\n");
outerValue.forEach((innerKey, innerValue) ->
System.out.println("int = " + innerKey + ", double = " + innerValue));
});
public static void main(String z[]) {
Map<Character, Map<Integer, Double>> MapInsideOfAMap = getmapOfMap();
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Char: " + outer.getKey() + "\n");
Map<Integer, Double> mapInner = MapInsideOfAMap.get(outer.getKey());
for (Map.Entry<Integer, Double> inner : mapInner.entrySet()) {
System.out.println(inner.getKey() +":"+ mapInner.get(inner.getKey()));
}
}
}
private static Map getmapOfMap() {
char[] chArr = {'a','b','c','d','e','f','g','h','i','j','k'};
HashMap<Character, Map<Integer, Double>> mapInsideOfAMap = new HashMap<Character, Map<Integer, Double>>();
for(char ch:chArr) {
mapInsideOfAMap.put(ch, getInnterMap());
}
return mapInsideOfAMap;
}
private static Map getInnterMap() {
Map<Integer, Double> map = new HashMap<>();
for(int i=1000;i<1010;i++) {
map.put(i, new Double(String.valueOf(i)));
}
return map;
}
In the second for-loop, you need to access the Map you get as a value from the outer loop.
You also need to change the type of the Entry in the second loop.
Try this code:
for (Entry<Character, Map<Integer, Double>> outer : MapInsideOfAMap.entrySet()) {
System.out.println("Key: " + outer.getKey() + "\n");
for (Entry<Integer, Double> inner : outer.getValue().entrySet()) {
System.out.println("Key = " + inner.getKey() + ", Value = " + inner.getValue());
}
}
But the complexity of the structure is probably redundant.
public static void print(char keyData, Map<Character, Map<Integer, Double>> fromData) {
System.out.println("print: " + get(keyData, fromData));
}
public static Map<Integer, Double> get(char keyData, Map<Character, Map<Integer, Double>> fromData) {
for (Map.Entry<Character, Map<Integer, Double>> entry : fromData.entrySet()) {
Character key = entry.getKey();
if(key.equals(keyData))
return entry.getValue();
}
return Collections.emptyMap();
}

How to get count the same values from HashMap?

How to get count the same values from HashMAP?
HashMap<HashMap<String, Float>, String> HM=new HashMap<HashMap<String,Float>, String>();
HashMap<String, Float> h;
h=new HashMap<String, Float>();
h.put("X", 48.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 320.0f);
HM.put(typeValuesHM, "Blue");
h=new HashMap<String, Float>();
h.put("X", 336.0f);
h.put("Y", 560.0f);
HM.put(typeValuesHM, "Blue");
The values of my HashMap HM are as follows:
{ {x=48,y=80}=Red,{x=192,y=80}=Red,{x=192,y=320}=Blue,{x=336,y=560}=Blue }
Here,
I want to count the similar values in the HashMap HM.
ie) if i give value equals to "Red" means i want to get count=2.
if i give value equals to "Blue" means i want to get count=2.
How to get count the same values from HashMAP HM?
int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
Loop through the entry set and drop all values to a second map, the first maps value as a key, the value will be the count:
Map<String, Integer> result = new TreeMap<String, Integer>();
for (Map.Entry<Map<String, Float>> entry:HM.entrySet()) {
String value = entry.getValue();
Integer count = result.get(value);
if (count == null)
result.put(value, new Integer(1));
else
result.put(value, new Integer(count+1));
}
The result map for your example should be like this:
{"Red"=2, "Blue"=2} // values are stored as Integer objects
The only way you can do it is to iterate through all the elements and count the occurrences:
for(String value: hm.values()) {
if (value.equals(valueToCompare)) {
count++;
}
}
int countValue(String toMatch) {
int count = 0;
for (String v : HM.values()) {
if (toMatch.equals(value)) {
count++;
}
}
return count;
}
Also, it is probably overkill to use a HashMap as the key if you are just storing two values. The built in Point uses int, but it would not be hard to re-implement with float.
Iterator<String> iter = HM.values().iterator();
while(iter.hasNext()) {
String color = iter.next();
if(color.equals("Red")) {
} else if(color.equals("Green")) {
} else if(color.equals("Blue")) {
}
}

Categories