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

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());
}

Related

How to get two different keys inside a foreach keySet()?

I want to print the keys of my HashMap "allDishes".
This HashMap contains an Dish as the value.
The Dish class has a HashMap field named "Ingredients".
I want to print the key of the "allDishes" and the keys of its HashMap "Ingredients".
With the foreach keySet(),
the key for Ingredients is "null",
because there is no value in "Ingredient" like there is in "allDishes".
Is it possible at all to print keys of different HashMaps?
Map<String, Dish> allDishes = (Map<String, Dish>) application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> Ingredient = allDishes.get(key).getIngredients();
out.println("<li><b>" + key + "</b> with: </li>" + Ingredient.get(key));
}
You are doing it wrong.
Currently,
you are iterating through the keys of the allDishes HashMap.
What you want to do is iterate through the keys of the allDishes HashMap and
for each key in the allDishes HashMap,
iterate through the keys of Ingredient HashMap contained within the current dish in the allDishes HashMap.
To do this,
first iterate through the allDishes entrySet,
then iterate through the ingredients keySet for each entry.
Here is some code:
final Map<String, Dish> dishMap = (Map<String, Dish>)application.getAttribute("allDishesHashMap");
for (final Map.Entry dishEntry: dishMap.entrySet())
{
final Map <String, String> ingredientMap = dishEntry.getIngredients();
out.println("<li><strong>" + dishEntry.getKey() + "</strong> Ingredients: <ul>");
for (final String ingredientName : ingredientMap.keySet())
{
out.println("<li>" + ingredientName + "</li>")
}
out.println("</ul></li>");
}
You can print them with nested loops and a null check.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String dishKey : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(dishKey).getIngredients();
System.out.println("Dish Key: " + dishKey);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
for (String ingredient : ingredients.keySet()) {
System.out.println("Ingredient Key: " + ingredient);
}
}
You can also print a "keyset" directly like the following if you don't need any special formatting on the keysets.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(key).getIngredients();
System.out.println("Dish Key: " + key);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
System.out.println("Ingredients KeySet: " + ingredients.keySet());
}

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.

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

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.

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);
});

Categories

Resources