Using a hashmap to iterate over a list of hashmaps - java

I am using a hashmap to add similar values for each aclLine processed
for (String aclLine : refinedFileContents){
if(Some condition)
{
staticVariablesMap.put("lineNumber", **lineNumber**);
staticVariablesMap.put("**srcHostName**", batchBean.getSourceIpAddress());
staticVariablesMap.put("batchBean", batchBean);
}
}
Later I want to iterate over these hashmaps for each line and perform some actions specific to a given key, value pair (e.g. get the srcHostName for that lineNumber) and use it to process next steps. How can I iterate over these collected hashmaps for each srcHostName entry in the hashmap? Should I use ArrayList/List to store each instance of the hashmap? Is this feasible?

Sounds to me like you should combine the attributes in your hashmaps into an object instead. Then you could just use one hash map.
public class AclLine {
private long lineNumber;
private String srcHostName;
private Object batchBean;
}
Map<AclLine> lines = new HashMap<AclLine>();
// Or maybe a List?
List<AclLine> lines = new ArrayList<AclLine>();
Or is there a reason you need these "parallel" map entries?

I didn't get your question completely like you are putting values in only one hash map & you want to iterate hashmaps
You can iterate hash map like this.
Iterator<Entry<String, Object>> it = hashMap.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, Object> entry = (Map.Entry<String, Object>)it.next();
}

Related

Java Iterate through a HashMap<?, List<?>> and for each Key count how many Values the Key has

I'm having problems on how to tackle this since I know a map has no specific order. I would think that you would iterate over the map's Keys and then check the value count by getting the size of the LinkedList since the Values to the Key are held in a LinkedList I can just call a size or length call for the LinkedList, but my main question is how to get inside the HashMap with an iterator first to do this?
An iterator over all the entries of a map can be done as follows in Java:
for (Map.Entry<Key, Value> entry : map.entrySet()) {
Key k = entry.getKey();
Value v = entry.getValue();
// do something with k,v
}
However, a map can only contain at most one value associated with a key. So, if using a map of lists to associate multiple values, the list would be accessed simply through get.
I suppose you have something like this :
Map<Integer,List<Integer>> map = new HashMap<>();
You can just iterate very simply through all the values you have.
for (List<Integer> values : map.values()){
System.out.println(values.size());
}

Return a value from Map

I have Map in Java
Map<String, List<String>> Collections;
String - a parents to ExpandtableList
List -a children to Expandtable List
Example Values
<"12" , "5,6,7,8">
<"15" , "4,6,2,8">
<"17" , "1,6,7,8">
<"8" , "5,6,6,8">
I'd like to get second parent and atribute to temporary String variable.(it is a "17") How can i refer to 2-nd parent and return value ?
There is no ordering in HashMap. If you want to focused on Order with Map you should use LinkedHashMap.
Use LinkedHashMap instead of HashSet. LinkedHashMap will maintain the insertion order.
Well, if you want "17" then you can just write map.get("17") to get the List.
Java doesnt keep track of the order here as it uses a Set to store the data. map.keySet() will return you a set you can iterate through.
You can HOPE that 17 falls under the natural ordering that Java does and do something like this.
HashMap<String, List<String>> map = new HashMap<>();
int count = 0;
for (String key : map.keySet()) {
count++;
if (count == 2)
return map.get(key);
}
If you want to retain an order in a Map, your usual choice would be a LinkedHashMap. With a linked hash map, you do however still not have direct access to an entry by its index. You would need to write a helper function:
static List<String> indexList(LinkedHashMap<String, List<String>> map, int index) {
int i = 0;
for(Map.Entry<String, List<String>> entry : map.entrySet()) {
if(i++ == index) {
return entry.getValue();
}
}
throw new IndexOutOfBoundException();
}
When using maps that point to a list, you might also be interested in using Guava's Multimap.

Getting first the first thing in HashMap? [duplicate]

This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 9 years ago.
So i've created an hashmap, but i need to get the first key that i entered.
This is the code i'm using:
First:
public static Map<String, Inventory> banks = new HashMap<String, Inventory>();
Second:
for(int i = 0; i < banks.size(); i++) {
InventoryManager.saveToYaml(banks.get(i), size, //GET HERE);
}
Where it says //GET HERE i want to get the String from the hasmap.
Thanks for help.
HashMap does not manatain the order of insertion of keys.
LinkedHashMap should be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).
You can use the MapEntry method to iterate over your the LinkedHashMap. So here is what you need to do in your code. First change your banks map from HashMap to the LinkedHashMap:
public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>();
And then simply iterate it like this:
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
If you just need the first element of the LinkedHashMap then you can do this:
banks.entrySet().iterator().next();
Answering the question in the title: to get the first key that was inserted, do this:
public static Map<String, Inventory> banks
= new LinkedHashMap<String, Inventory>();
String firstKey = banks.keySet().iterator().next();
Notice that you must use a LinkedHashMap to preserve the same insertion order when iterating over a map. To iterate over each of the keys in order, starting with the first, do this (and I believe this is what you intended):
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}

HashMap<String, Integer> Search for part of an key? [duplicate]

This question already has answers here:
Partial search in HashMap
(5 answers)
Closed 6 years ago.
I am currently using HashMap<String, Integer> which is filled with keys of type String which are all, let's say, 5 chars long. How can I search for an specific key of 4 chars or less, which is part and at the beginning of some other keys and get all hits as a collection of <Key, Value>?
Iterate is your only option unless you create a custom data structure:
for (Entry<String, Integer> e : map.entrySet()) {
if (e.getKey().startsWith("xxxx")) {
//add to my result list
}
}
If you need something more time efficient then you'd need an implementation of map where you are tracking these partial keys.
It seems like a use case for TreeMap rather than HashMap. The difference is that TreeMap preserves order. So you can find your partial match much quicker. You don't have to go through the whole map.
Check this question Partial search in HashMap
You cannot do this via HashMap, you should write your own implementation for Map for implementing string length based searching in a map.
Map<String, Integer> result = new HashMap<String, Integer>;
for(String key : yourMap.keySet()) {
if(key.length() == 4){
result.put(key, yourMap.get(key);
}
}
After executing this code you have all key/value pairs with 4 letter keys in result.
Set<Entry<String, Integer>> s1 = map.entrySet();
for (Entry<String, Integer> entry : s1) {
if(entry.getKey().length == 4)
//add it to a map;
}
First get the entry set to your hashmap. Iterate through the set and check the length of each key and add it to a map or use it as u want it.
With HashMap<String, Integer> you can only go through keySet() and do contains() for String keys and your pattern.
As has been noted, there isn't a terribly efficient* way to do it with the datastructure you have specified. However, if you add an additional Map<Integer, List<String>> to keep track of the mapping from string length to the list of all keys with that length, then you will be able to do this very efficiently.
*Using just the Map<String, Integer>, you would need to iterate through the entire capacity of the larger map, whereas adding this supplemental datastructure would impose an O(1) lookup (assuming you used a HashMap) followed by iteration through just the result set, which is the fastest possible outcome.
You can try this approach:
public Map<String,Integer> filterMap(Map<String, Integer> inputMap){
Map<String, Integer> resultHashMap = new HashMap<String, Integer>();
for (String key : inputMap.keySet()) {
if(key.length()==5){
resultHashMap.put(key,inputMap.get(key));
}
}
return resultHashMap;
}

What is the best datastructure to use in Java for a "multidimensional" list?

I need a dictionary-like data structure that stores information as follows:
key [value 1] [value 2] ...
I need to be able to look up a given value by supplying the key and the value I desire (the number of values is constant). A hash table is the first thing that came to my mind but I don't think it can be used for multiple values. Is there any way to do this with a single datastrucuture rather than splitting each key-value pair into a separate list (or hash table)? Also I'd rather not use a multi-dimensional array as the number of entries is not known in advance. Thanks
I'm not sure what you mean about your list of values, and looking up a given value. Is this basically a keyed list of name-value pairs? Or do you want to specify the values by index?
If the latter, you could use a HashMap which contains ArrayLists - I'm assuming these values are String, and if the key was also a String, it would look something like this:
HashMap<String, ArrayList<String>> hkansDictionary = new HashMap<String, ArrayList<String>>();
public String getValue (String key, int valueIdx) {
ArrayList<String> valueSet = hkansDictionary.get(key);
return valueSet.get(valueIdx);
}
If the former, you could use a HashMap which contains HashMaps. That would look more like this:
HashMap<String, HashMap<String, String>> hkansDictionary
= new HashMap<String, HashMap<String, String>>();
----
public String getValue (String key, String name) {
HashMap<String, String> valueSet = hkansDictionary.get(key);
return valueSet.get(name);
}
You could make a class that holds the two key values you want to look up, implement equals() and hashcode() to check/combine calls to the underlying values, and use this new class as the key to your Map.
I would use
Map<Key,ArrayList<String>> map = new HashMap<Key,ArrayList<String>>
where you define Key as
public class Key{
private String key;
private String value;
//getters,setters,constructor
//implement equals and hashcode and tostring
}
then you can do
Key myKey = new Key("value","key");
map.get(myKey);
which would return a list of N items
You can create a multidimensional array by first declaring it, then creating a method to ensure that new value keys are initialized before the put. This example uses a Map with an embedded List, but you can have Maps of Maps, or whatever your heart desires.
I.e., you must define your own put method that handles new value initialization like so:
private static Map<String, List<USHCommandMap>> uSHCommandMaps = new HashMap<String, List<USHCommandMap>>();
public void putMemory() {
if (!uSHCommandMaps.containsKey(getuAtom().getUAtomTypeName()))
uSHCommandMaps.put(getuAtom().getUAtomTypeName(), new ArrayList<USHCommandMap>());
uSHCommandMaps.get(getuAtom().getUAtomTypeName()).add(this);
}

Categories

Resources