How to iterate and print nested HashMap with Integer as value? [duplicate] - java

This question already has answers here:
Multi-line pretty-printing of (nested) collections in Java
(4 answers)
Closed 6 years ago.
I want to print a nested HashMap which is :
HashMap<Integer,HashMap<Character,Integer>> map;
I searched a lot but I can't find a way to print the Integer because when I use getValues() on it, it tells me : "cannot find symbol". (Because it's an Integer value)
This is what I tried to do :
public void print(){
for(Map.Entry<Integer, HashMap<Character,Integer>> t :this.map.entrySet()){
Integer key = t.getKey();
for (Map.Entry<Character,Integer> e : this.map.getValue().entrySet())
System.out.println("OuterKey:" + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
}
}
I can't use getValue() in my second for, so what else can I use ?
Thanks in advance !
Have a nice day.
Chris.

getValue() is a method of Map.Entry, not Map.
You should use t.getValue().entrySet() instead of this.map.getValue().entrySet() in the second loop.
That would give you the inner Map.
public void print(){
for(Map.Entry<Integer, HashMap<Character,Integer>> t :this.map.entrySet()){
Integer key = t.getKey();
for (Map.Entry<Character,Integer> e : t.getValue().entrySet())
System.out.println("OuterKey:" + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
}
}

The easiest way to print the whole thing:
System.out.println(map.toString());
Yep, thats it; toString() returns a string ... that contains all the content of your Map; including its inner Map!
If you want to do that yourself, then you can use two loops:
for(Map.Entry<Integer, HashMap<Character,Integer>> innerMap : map.entrySet()) {
for (Map.Entry<Character, Integer> aMap : innerMap.entrySet) {
... now you can call aMap.getKey() and .getValue()

public static void main(String[] args) {
HashMap<Integer,HashMap<Character,Integer>> map = new HashMap<Integer,HashMap<Character,Integer>>();
HashMap<Character,Integer> map1 = new HashMap<Character,Integer>();
map1.put('1', 11);
HashMap<Character,Integer> map2 = new HashMap<Character,Integer>();
map2.put('2', 22);
map.put(111, map1);
map.put(222, map2);
for (Integer temp : map.keySet()) {
for (Character c : map.get(temp).keySet()) {
System.out.println("key--" + c + "--value--" + map.get(temp).get(c));
}
}
}
Hope it works.

Related

Java Nested map String array Looping Optional<Map<String,Map<String,String[]>>>

I have an object of Optional<Map<String,Map<String,String[]>>> How do I loop over each string in the array?
The below code I am expecting "application" to be 'String' but it gives me 'String[]'
Optional<Map<String,Map<String,String[]>>> myObject = Optional.of(yamlReader.read(name, HashMap.class));
Set<Map.Entry<String, Map<String, String[]>>> abc = myObject.get().entrySet();
for ( Map.Entry<String, Map<String, String[]>> x:abc) {
Map<String, String[]> v = x.getValue();
//I am expecting "application" to be String here but it is an array of Strings for some reason
for (String[] application: v.values()) {
System.out.println(application + " " + x.getKey());
}
You need to iterate through the String[] to get individual values.
May be you might need to verify the given requirement with structure you are using now.
for (Map.Entry<String, Map<String, String[]>> x : abc) {
Map<String, String[]> v = x.getValue();
v.values().forEach(value -> {
System.out.println("value:" + " " + value);
});
}
it is an array of String because v.values() is Collection<String[]>, it is not just String. if you want to print only String, you would need to flat that out.
So if you end goal is to just print all Strings available in your collection, you can use below code.
myObject.ifPresent(map -> map.values().stream().map(Map::values).flatMap(Collection::stream).flatMap(Arrays::stream).forEach(System.out::println));
or if you would like to tweak your code, do something like below to replace your for last loop
v.values().stream().flatMap(Arrays::stream).forEach(application -> System.out.println(application + " " + x.getKey()));
OR
for (String[] application: v.values()) {
System.out.println(Arrays.asList(application) + " " + x.getKey());
}

Java Printing all of my maps keys and values

Quick question and its probably the most simple answer but i need to print a textual representation of my HashMaps contents.
My code so far is:
public void printAll() {
Set< String> Names = customersDetails.keySet();
Collection< CustomerDetails> eachCustomersNames = customersDetails.values();
for (String eachName : Names) {
System.out.println(eachName)
}
for (CustomerDetails eachCustomer : eachCustomersNames) {
System.out.println(eachCustomer);
}
}
But this results in the list of keys and then a list of values but i need each line of text to read something like
Bob [example]
Where Bob is the key and example is the value.
If you're using Java 8, you can take advantage of lambda syntax and .forEach() like so:
customersDetails.forEach((k,v) -> {
System.out.println(k + "[" + v + "]");
});
Where k is your key and v is the value tied to key k.
Every key maps to just one value, so you can just do this:
Set < String> Names = customersDetails.keySet();
for (String eachName: Names) {
System.out.println(eachName + " [" + customersDetails.get(eachName).toString() + "]")
}
If you're not using Java 8, simply print both key and value for each key:
for (String eachName : Names) {
System.out.println(eachName + " [" + customersDetails.get(eachName) + "]");
}
You can print your Map like so :
Map<String, String> customersDetails = new HashMap<>();
for (Map.Entry<String, String> entry : customersDetails.entrySet()) {
System.out.println(entry.getKey() + '[' + entry.getValue() + ']');
}
If you are using java 8 you can use :
customersDetails.entrySet().forEach((entry) -> {
System.out.println(entry.getKey() + '[' + entry.getValue() + ']');
});
If you start dealing with maps with more complicated types consider using ReflectionToStringBuilder. Internally it uses reflection to build a string of an object and its fieldd. It recurses through the object graph too.
It may not be efficient, but it helps a lot with debugging and printing operations.
You don't need to iterate over your keys/values in order to print your map, as the HashMap.toString() method already does this for you very efficiently (actually, it's the AbstractMap.toString() method).
If you have your CustomerDetails class implement the toString() method, then you only need to do:
System.out.println(customerDetails);
And this will print your map in the format you require.

Get the key and value of Map that is used Inside another Map (JAVA)

I am using a map inside another map, The key of the outer map is Integer and the value is another Map. I get the values as expected but I don't know how to get the key and value of teh inner map.
Here is the code
Map<Integer, Map<Integer, Integer>> cellsMap = new HashMap<Integer, Map<Integer, Integer>>();
Map<Integer , Integer> bandForCell = cellsMap.get(band_number);
if (bandForCell == null)
bandForCell = new HashMap<Integer, Integer>();
bandForCell.put(erfcn, cell_found);
cellsMap.put(band_number, bandForCell);
csv.writeCells((Map<Integer, Map<Integer, Integer>>) cellsMap);
public void writeCells (Map<Integer, Map<Integer, Integer>> cellsMap ) throws IOException
{
for (Map.Entry<Integer, Map<Integer, Integer>> entry : cellsMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
}
}
Out put of my Map
Key: 20 Value: {6331=0, 6330=1, 6329=1, 6328=0, 6335=1, 6437=0, 6436=1}
The value in the above output is another map.
How can I get the key and value of the inner map from the value of the outer map?
Like Keys of inner map = 6331, 6330, 6329 ....
and values of inner map = 0 , 1 , 1 , 0 ...
Thanks
This worked for me , Hope it will help someone else in future
for (Map.Entry<Integer, Map<Integer, Integer>> outer : cellsMap.entrySet()) {
System.out.println("Key: " + outer.getKey() + "\n");
for (Map.Entry<Integer, Integer> inner : entry.getValue().entrySet()) {
System.out.println("Key = " + inner.getKey() + ", Value = " + inner.getValue());
}
}
In order to get a reference to an inner map, you would just use cellsMap.get(key). I'm not sure exactly what you want to do, but, for example, if you wanted to get the value where the first key was i and the second key was j, you could get it using cellsMap.get(i).get(j)
Or, if you wanted to print out all the keys and values of the inner map at index i, you could use
for (Map.Entry> entry : cellsMap.get(i).entrySet()) {
System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
}

Java - Iterating over a Map which contains a List

First time here so I hope this makes sense!
I have a Map which contains a String as it's Key, and a List of Strings as it's Value. I need to iterate over all vlaues contained within each List within the Map.
So, first I want to get the Keys, which works:
Set<String> keys = theMap.keySet();
This returns me a Set containing all my Keys. Great :)
This is where I've got stuck - most of the info on the web seems to assume that the values I'd want returned from the Key would be a simple String or Integer, not another Set, or in this case a List. I tried theMap.values() but that didn't work, and I tried a forloop / for:eachloop, and neither of those did the trick.
Thanks y'all!
for(List<String> valueList : map.values()) {
for(String value : valueList) {
...
}
}
That's really the "normal" way to do it. Or, if you need the key as well...
for(Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
...
}
}
That said, if you have the option, you might be interested in Guava's ListMultimap, which is a lot like a Map<K, List<V>>, but has a lot more features -- including a Collection<V> values() that acts exactly like what you're asking for, "flattening" all the values in the multimap into one collection. (Disclosure: I contribute to Guava.)
I recommend iterating over Map.entrySet() as it is faster (you have both, the key and the value, found in one step).
Map<String, List<String>> m = Collections.singletonMap(
"list1", Arrays.asList("s1", "s2", "s3"));
for (Map.Entry<String, List<String>> me : m.entrySet()) {
String key = me.getKey();
List<String> valueList = me.getValue();
System.out.println("Key: " + key);
System.out.print("Values: ");
for (String s : valueList) {
System.out.print(s + " ");
}
}
Or the same using the Java 8 API (Lambda functions):
m.entrySet().forEach(me -> {
System.out.println("Key: " + me.getKey());
System.out.print("Values: ");
me.getValue().forEach(s -> System.out.print(s + " "));
});
Or with a little bit of Java Stream API mapping hardcore and method reference :-)
m.entrySet().stream().map(me -> {
return "Key: " + me.getKey() + "\n"
+ "Values: " + me.getValue().stream()
.collect(Collectors.joining(" "));
})
.forEach(System.out::print);
And the output is, as expected:
Key: list1
Values: s1 s2 s3
You need a Map<String, List<String>>
The left hand side String is the key, the right hand side List<String> is the value, which in this case is a List of Strings
Another example with the Java 8 API (lambda function).
When you want to iterate over:
Map<String, List<String>> theMap = new HashMap<>();
theMap.forEach((key, value) -> {
System.out.println("KEY: " + key);
System.out.print("VALUES: ");
value.forEach(System.out::println);
});

Loop Java HashMap like Python Dictionary?

In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
Yes - for example:
Map<String, String> map = new HashMap<String, String>();
// add entries to the map here
for (Map.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.printf("%s %s\n", k, v);
}
The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.
I think is the closest thing to the Python version.
As shown in the answers, there are basically two ways to iterate over a Map (let's assume Map<String, String> in those examples).
Iterate over Map#entrySet():
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Iterate over Map#keySet() and then use Map#get() to get the value for every key:
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
The second one is maybe more readable, but it has a performance cost of unnecessarily calling get() on every iteration. One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. But believe it or not, the keySet().iterator() creates and uses the same iterator as entrySet().iterator(). The only difference is that in case of the keySet() the next() call of the iterator returns it.next().getKey() instead of it.next().
The AbstractMap#keySet()'s javadoc proves this:
The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator.
The AbstractMap source code also proves this. Here's an extract of keySet() method (somewhere around line 300 in Java 1.6):
public Iterator<K> iterator() {
return new Iterator<K>() {
private Iterator<Entry<K,V>> i = entrySet().iterator(); // <-----
public boolean hasNext() {
return i.hasNext();
}
public K next() {
return i.next().getKey(); // <-----
}
public void remove() {
i.remove();
}
};
}
Note that readability should be preferred over premature optimization, but it's important to have this in mind.
Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
System.out.println(i.getKey().toString() + i.getValue().toString);
}
Something like that...
In Java, you can do the same like the following.
HashMap<String, String> h = new HashMap<String, String>();
h.put("1","one");
h.put("2","two");
h.put("3","three");
for(String key:h.keySet()){
System.out.println("Key: "+ key + " Value: " + h.get(key));
}

Categories

Resources