Getting first the first thing in HashMap? [duplicate] - java

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

Related

How is the sequence decided when looping through map [duplicate]

This question already has answers here:
is the Java HashMap keySet() iteration order consistent?
(12 answers)
Closed 2 years ago.
I have a question about the sequence of hash map. For example, in the following code:
public class MapEntrySetOrder {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
String[] l = new String[]{"Entry", "Set", "HashMap", "Order"};
for (String s : l) {
map.putIfAbsent(s, s);
}
for(Map.Entry<String, String> e : map.entrySet()) {
System.out.println("key:" + e.getKey());
}
}
}
I know there is no order maintained in hashmap, but every time I print the keys thru a loop, there are all in same order, and the order is not from the beginning of the original list nor from the end of the original list:
key:Order
key:Entry
key:Set
key:HashMap
So how is the order decided. If it is in a random way, why every time I print they are the same result?
Use HashMap for fast non-ordered Map
Use LinkedHashMap for order of adding to the Map
Use TreeMap for any order you wish (with Comparator implementation)
Also I think you have same order each time because you use map.entrySet() instead of map.keySet()
Hashmap does not guarantee any order.
If you want ordered sequence use LinkedHashMap instead.

How to sort Hashmap of type Hashmap<String, Arraylist<String>> by value? [duplicate]

This question already has answers here:
Sorting hashmap based on keys
(9 answers)
Closed 3 years ago.
I want to sort the following hashmap by value. Hashmap is Hashmap<String, Arraylist<String>> and the data in it is as following:
924911637601767=[1, John]
864467483673342=[2, Paul]
825398867568656=[8, James]
1034643283235161=[5,Elina]
I want to sort the above data with respect to the counter values i.e 1,2,8,5
After Sorting
924911637601767=[1, John]
864467483673342=[2, Paul]
1034643283235161=[5,Elina]
825398867568656=[8, James]
HashMap no guarantees as to the order.
If you want get list by order like you want, you should sort list values of the HashMap.
Example can be found here How to sort a HashMap in Java
This class makes no guarantees as to the order of the map; in particular, it >does not guarantee that the order will remain constant over time.
See http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
In other words, what you are looking for cannot be achieved as you want.
However, what you can do is to transform your Hashmap to a list of objects that consist of each map entry elements.
Object: key, name, number for example.
Your object can then implement java.lang.Comparable in order to sort it as you want.
See https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
The hashmap abstract data type is inherently unsorted. Depending on your use case, you could do something like:
import java.util.*;
class Test {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.put("924911637601767", Arrays.asList("1", "John"));
map.put("864467483673342", Arrays.asList("2", "Paul"));
map.put("825398867568656", Arrays.asList("8", "James"));
map.put("1034643283235161", Arrays.asList("5", "Elina"));
List<Map.Entry<String,List<String>>> entries = new ArrayList<Map.Entry<String,List<String>>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String,List<String>>>() {
public int compare(Map.Entry<String,List<String>> l1, Map.Entry<String,List<String>> l2) {
return l1.getValue().get(0).compareTo(l2.getValue().get(0));
}
});
for (Map.Entry<String,List<String>> e : entries) {
System.out.println(e.getKey() + " : [" + e.getValue().get(0)
+ ", " + e.getValue().get(1) + "]");
}
}
}
Use the sortedMap Interface if you are interested in sorted order and also want to keep a map.
TreeMap could be a choice.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

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

Using a hashmap to iterate over a list of hashmaps

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

HashMap keys and values [duplicate]

This question already has answers here:
Does Java have a HashMap with reverse lookup?
(7 answers)
Closed 9 years ago.
I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?
My Map is
Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");
Now i want to create an another map and put it in other way as i told above. ie,
Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");
Anybody has idea? Thanks
Like so:
Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
col2.put(e.getValue(), e.getKey());
}
Assuming your values are unique in your hashmap, you can do like this.
// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
String currentValue = valueIterator.next();
// Find the value in old HashMap
Iterator<String> keyIterator = col.keySet().iterator();
while(keyIterator.hasNext()){
String currentKey = keyIterator.next();
if (col.get(currentKey).equals(currentValue)){
// When found, put the value and key combination in new HashMap
col1.put(currentValue, currentKey);
break;
}
}
}
Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.

Categories

Resources