How do I iterate over a LinkedHashMap of LinkedHashMaps? - java

My map looks like this :
LinkedHashMap <LinkedHashMap <String,String>,LinkedHashMap <String,String>> leftRightWords
Where the first map contains left words of a proper noun and second map contains right words of a proper noun. E.g. in :
"Following the Rhode Island solution provider Atrion's decision to
sell"
map1 will have entries like:
Rhode Island, Following the
Atrion, solution provider
map2 will have entries like:
Rhode Island, solution provider
Atrion, decision to sell
In both maps the keys are the same but the values differ based on left and right words. How do i iterate over this map to extract the left words and right words to analyze them?

You can use a nested forEach loop to extract the data you desire, like so:
for(LinkedHapMap<String, String> lhm: leftRightWords.keySet()){
for(String k:lhm.keySet()){
String left = lhm.get(k);
String right = leftRightWords.get(lhm).get(k);
//do something with these Strings
}
}

You can do it this way:
Iterator<LinkedHashMap<String, String>> resultKeys = leftRightWords
.keySet().iterator();
while (resultKeys.hasNext()) {
LinkedHashMap<String, String> tempKey = resultKeys.next();
LinkedHashMap<String, String> tempVal = leftRightWords.get(tempKey);
System.out.println("Key:");
for (Map.Entry<String, String> entry : tempKey.entrySet()) {
System.out.println(entry.getKey() + " "
+ entry.getValue());
}
System.out.println();
System.out.println("Value:");
for (Map.Entry<String, String> entry : tempVal.entrySet()) {
System.out.println(entry.getKey() + " "
+ entry.getValue());
System.out.println();
}
}

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: Iterate through a HashMap which is inside another HashMap

I want to iterate through a HashMap which is inside another HashMap
Map<String, Map<String, String>> PropertyHolder
I was able to iterate through the parent HashMap as following,
Iterator it = PropertyHolder.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println("pair.getKey() : " + pair.getKey() + " pair.getValue() : " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
but could not able to iterate through the child Map, It can be done by converting pair.getValue().toString() and separated using , and =. Is there any other way of iterating it?
for (Entry<String, Map<String, String>> entry : propertyHolder.entrySet()) {
Map<String, String> childMap = entry.getValue();
for (Entry<String, String> entry2 : childMap.entrySet()) {
String childKey = entry2.getKey();
String childValue = entry2.getValue();
}
}
You could iterate the child map similar to how you've done the parent:
Iterator<Map.Entry<String, Map<String, String>>> parent = PropertyHolder.entrySet().iterator();
while (parent.hasNext()) {
Map.Entry<String, Map<String, String>> parentPair = parent.next();
System.out.println("parentPair.getKey() : " + parentPair.getKey() + " parentPair.getValue() : " + parentPair.getValue());
Iterator<Map.Entry<String, String>> child = (parentPair.getValue()).entrySet().iterator();
while (child.hasNext()) {
Map.Entry childPair = child.next();
System.out.println("childPair.getKey() : " + childPair.getKey() + " childPair.getValue() : " + childPair.getValue());
child.remove(); // avoids a ConcurrentModificationException
}
}
I've presumed you want to call .remove() on the child map, which will lead to a ConcurrentModificationException if done while looping the entrySet - it looks as though you discovered this already.
I've also swapped out your use of casting with strongly-typed generics as suggested in the comments.
It's obvious - you need two nested loops:
for (String key1 : outerMap.keySet()) {
Map innerMap = outerMap.get(key1);
for (String key2: innerMap.keySet()) {
// process here.
}
}

Get value of HashMap within TreeMap

I've got a TreeMap that stores a HashMap inside of it. I feel like I should be able to find this, but I just can't seem to find it on Google.
I've got a TreeMap with a HashMap stored inside of it, I iterate over it like so:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
That will print out an output (example line):
I/System.outīš• 32: {walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
I'm wondering how to now grab pic, name, dist from this HashMap.
Edit: I'm not understanding where people missed the point. I put a HashMap into the TreeMap. Inside of the TreeMap is a HashMap. I guess I can show you what a HashMap is, but you guys know that already!
TreeMap dist_mp=new TreeMap();
Map<String, String> mp1 = new HashMap<String,String>();
mp1.put("dist", distanceInMiles + "");
mp1.put("name", obj.getString("first_name"));
mp1.put("pic", obj.getString("pic"));
mp1.put("walks", obj.getString("walks"));
dist_mp.put(distanceInMiles, mp1);
All you need is a cast to the TreeMap values to a Map again:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
// Cast to a Map again
Map<String, String> mp = (Map<String, String>) me.getValue();
// get() works now
System.out.print("name = " + mp.get("name"));
System.out.print("pic = " + mp.get("pic"));
System.out.println("dist = " + mp.get("dist"));
}
Need to iterate twice, one for TreeMap and then for HashMap
public static void main(String[] args) {
TreeMap<String, Map<String, String>> dist_mp = new TreeMap<String, Map<String, String>>();
Map<String, String> mp1 = new HashMap<String, String>();
mp1.put("dist", "6096.8589024135445");
mp1.put("name", "Chase");
mp1.put("pic", "http://****/images/walkers/chase.png");
mp1.put("walks", "32");
dist_mp.put("32", mp1);
for (Map.Entry<String, Map<String, String>> entry : dist_mp.entrySet()) {
String key = entry.getKey();
System.out.println(key);
Map<String, String> myMap = entry.getValue();
for (Map.Entry<String, String> entry1 : myMap.entrySet()) {
System.out.println(entry1.getKey() + " => " + entry1.getValue());
}
}
}
output
32
walks => 32
name => Chase
pic => http://****/images/walkers/chase.png
dist => 6096.8589024135445
Your HashMap seems to be holding an object of some class, which is depicted here:
{walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
Identify the class, and if getter methods are available for pic, name, dist, then use them.
I think you are just asking how to get the value associated with a key:
map.get("pic");
You want me.getValue().get("pic"), me.getValue().get("name") and me.getValue().get("dist").
This assumes that you're using generics, that your TreeMap is declared as a Map<Integer, HashMap<String, String>> and that your Map.Entry that you iterate with is declared as a Map.Entry<Integer, HashMap<String, String>>.
Also, you could iterate more easily with a for-each loop.
Map<Integer, HashMap<String, String>> theTreeMap = new TreeMap<>();
// Populate the map here.
for (Map.Entry<Integer, HashMap<String, String>> me : theTreeMap.entrySet()) {
System.out.println(me.getValue().get("pic"));
System.out.println(me.getValue().get("name"));
System.out.println(me.getValue().get("dist"));
}

Java - How can I get a single pair from a LinkedHashMap?

Specifically, I want to use a LinkedHashMap in a "for each" loop. For example, let's say I create a LinkedHashMap:
LinkedHashMap<String, Integer> someHash = new LinkedHashMap<String, Integer>();
Then I fill it with some things:
someHash.put("One", new Integer(1));
someHash.put("Two", new Integer(2));
Now how might I be able to go through and get each pair? I want something along the lines of:
for(<String, Integer> pair : someHash)
{
//Do stuff.
}
But of course this doesn't work. Is there a simple way to retrieve a "pair" object from the hash? Or do I just have to iterate through the length and get the value and key separately? Also, should I really be using a different object if this is the case?
You can use Map.Entry to simulate the Pair object that exists in C++.
for(Map.Entry<String, Integer> entry : someHash.entrySet())
{
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
Here the entrySet is the all key/value pairs from your Map.
Use like this
LinkedHashMap<String, Integer> someHash = new LinkedHashMap<String, Integer>();
someHash.put("One", new Integer(1));
someHash.put("Two", new Integer(2));
for(String key : someHash.keySet())
{
System.out.println("Key : "+key + " Value : "+someHash.get(key));
}

Find duplicates in array list using Map<String, Integer> with input order

Hi everyone I am trying to print all the duplicated elements, this works fine but the outputs are not in order (either from user input or from the text file).
I want to print all elements with order (duplicates are not printed). How do I do that?
The codes are from this Find the duplicate elements in arraylist and display
Thanks #Cory Kendall for the codes.
**********updated question: the code now works perfect with LinkedHashMap. Now I want the outputs to be printed with number bullets (ie, 1. name1 = 2 ) incrementally. Thanks
List<String> strings = new ArrayList<String>();
// suppose datas are entered by user incrementally or from a text files.
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String str : strings) {
if (counts.containsKey(str)) {
counts.put(str, counts.get(str) + 1);
} else {
counts.put(str, 1);
}
}
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
If you want to remember insertion order in your Map, you need to use LinkedHashMap. In your case you have to replace
Map<String, Integer> counts = new HashMap<String, Integer>();
with
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
HashMap is not ordered or sorted, use LinkedHashMap if you care about insertion order, or use TreeMap if you care about natural order.
public class FindDup {
public static void main(String[] args) {
String str[] = { "yogi", "ram", "ram", "yogi", "yogi", "yogi", "raju", "raju", "ram", "yogi", };
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : str) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
for (Entry<String, Integer> e : map.entrySet()) {
System.out.println(e.getKey() + "---" + e.getValue());
}
}
}
A LinkedHashMap will retain order.
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
About LinkedHashMap:
Hash table and linked list implementation of the Map interface, with
predictable iteration order. This implementation differs from HashMap
in that it maintains a doubly-linked list running through all of its
entries. This linked list defines the iteration ordering, which is
normally the order in which keys were inserted into the map
(insertion-order).

Categories

Resources