How can I get a value from Hashmap<String, Object>? - java

I need a Map that can have values of any type. So I've tried to use HashMap. However, if I try to get a value from the map, the IDE says that the type doesn't match.
This is a part of my code with the matter:
Map<String, Object> state1 = new HashMap<>();
state1.put("location", exit1);
state1.put("direction", direction);
state1.put("number", 0);
Deque<Map> q = new ArrayDeque<>();
q.add(state1);
List<Integer> numbers = new ArrayList<>();
while (!q.isEmpty()) {
Map<String, Object> state = q.poll();
Pair location = state.get("location");
The variables exit1, direction are already defined before this part, so you may ignore about that. Also, you don't have to care about the code below this part.
My IDE says that the line Map<String, Object> state = q.poll(); has incompatible types — Pair is required but Object is found. How can I make this compatible?
I am working on a problem that can run only one file, so I can't implement a new class.

...
Pair location = null;
if(state.get("location") instanceof Pair){
Pair location = (Pair)state.get("location");
}
else{
...
}

You can specify the generic type like this:
Deque<Map<String, Object>> q = new ArrayDeque<>();

Related

How can i convert Map of Strings and Object to a Map of Strings and List

I have method that should return Map<Strings, List<String>> but in the mean time my method gives me a Map<Strings, Object>, I want to transfer the values of object into a List of Strings.
Here is the current code:
#SuppressWarnings("unchecked")
static Map<String, List<String>> getQueryParameters(JsonObject inputJsonObject) {
JsonArray parameters = inputJsonObject.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).findFirst();
Map<String, Object> paramMap = queryParameters.get().getMap();
paramMap contains key and value , values could be an arrays of integers
so I want to put them into the map below:
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
My solution is this which did not work correctly
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
Map<String, Object> paramMap = queryParameters.get().getMap();
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
if (!mystore.containsKey(key)) ;
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
}
I was a key holding another key as value and is just a mix up , any suggestions?
After debuging what happens i see that mystore holds both "key and value" together as a key and value it hold the next "key and value as value
Should be something like this:
while (it.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
String key = next.getKey();
Object value = next.getValue();
if (!mystore.containsKey(key)) mystore.put(key, new LinkedList<String>());
mystore.get(key).add(value.toString());
}
I'm not writing a program for you, but instead help you in finding a problem. You are confused with Entry. If you are using IDE, you should solve it easier. Look for this line :
String key = it.next().toString();
Entry has a K,V pair. The iterator returns an EntrySet and thus usage to get key is it.next().getKey() and it.next().getValue()
Now that you have a correct key, please go on debugging. Instead of putting and getting and manipulating in below lines of your code. Put with correct value instead?
Yours:
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
What about?:
Entry entry = it.next();
//Get key and value here. DO coding using Entry's methods
List<String> ll = new LinkedList<String>();
ll.add(value)
mystore.put(key, ll);
Tip: Always have the Javadoc or reference documentation handy for knowing more. That's how you learn the language. Refer:https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html

Java How to access hash map data held in an array

learning Java and have figured out how to store a hashmap in an array. But I can't figure out how to get to the stored data. Here is a simplified version of what I'm doing. I've got as far as displaying the specific array items, but how do I access the hash map stored in the array?
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Map<String, String> custOrder = new HashMap<String, String>();
List ordersPlaced = new ArrayList();
custOrder.put("colour", "blue");
custOrder.put("manu", "bmw");
custOrder.put("body", "4x4");
ordersPlaced.add(custOrder);
custOrder = new HashMap();
custOrder.put("colour", "green");
custOrder.put("manu", "merc");
custOrder.put("body", "saloon");
ordersPlaced.add(custOrder);
System.out.println(ordersPlaced.get(0).toString());
}
}
Hope that makes sense. Thanks in advance
Neil
You're already accessing it.
In order to get the iterate on the map's items, you can:
ordersPlaced.get(0).forEach((key, value) -> {
System.out.println("Key is: " + key + ", Value is: " + value);
});
Or, earlier to Java 8, something like:
for (Map.Entry<String, String> entry : ordersPlaced.get(0).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
Please note that you should avoid using raw type list. Instead, you should have:
List<Map<String, String>> ordersPlaced = new ArrayList<>();
And then:
Map<String, String> m = ordersPlaced.get(0);
You know it already.
You can get back the stored map by writing
Map<String, String> placedCustOrder = ordersPlaced.get(0);
And avoid using raw types while using List. Declare your list as
List<Map<String, String>> ordersPlaced = new ArrayList<>();
I would like to know how to access the colour of the data stored in the array at location 0
Since you got the map as I said in the line 1
Map<String, String> placedCustOrder = ordersPlaced.get(0);
String colorVal = placedCustOrder.get("colour");
I strongly suggest you to look through Map documentation before proceeding further.

Single Key Multiple Accounts to Map

My map is declared as private Map accountByReport;
I am using the below loop to check if the reportID is in the map or not before adding the corresponding Department Account to the key. Is my loop correct and what should the type declaration be in this instance and how can I catch exceptions?
for(Entity entity : entities) {
if(accountsByReport.containsKey(entity.getReportID())) {
((List<String>)accountsByReport.get(entity.getReportID())).add(entity.getDepAccount());
} else {
accountsByReport.put(entity.getReportID(), new ArrayList<String>().add(entity.getDepAccount()));
}
}
It seems you are adding a boolean (the return ok .add()) to the map in the else.
I would use this way:
for(Entity entity : entities) {
if(accountsByReport.containsKey(entity.getReportID())) {
((List<String>)accountsByReport.get(entity.getReportID())).add(entity.getDepAccount());
} else {
List<String> list = new ArrayList<String>();
list.add(entity.getDepAccount());
accountsByReport.put(entity.getReportID(), list);
}
}
You didn't paste the Map definition, but you should use typed parameters - i.e. Map<String, List<String>> accountsByReport = new HashMap<String, List<String>>(); so you don't need to do casting after .get
In fact you pasted it.
Use: private Map<String, List> accountByReport;
Refer to http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Your code is correct so far, but your Map should declare with type
The map should be declared based on the type of reportID,
//if String
private Map<String, List<String>> accountByReport;
//if int
private Map<Integer, List<String>> accountByReport;
//so on
Your loop is essentially correct. The only improvements you can make is to do a single get and store the result rather than doing both a contains and a get. You should also use generics so you don't need the cast..
List<String> list = accountsByReport.get(entity.getReportID())
if(list != null) {
list.add(entity.getDepAccount());
} else {
accountsByReport.put(entity.getReportID(), new ArrayList<String>().add(entity.getDepAccount()));
}

Converting Each Value in static HashMap to String Java

I have got some troubles converting each value in my HashMap to a String.
private static HashMap<String, List<Music>> musiksammlung = new
HashMap<String, List<Music>>();
This is my constructor for the HashMap. The key represents the album, the value a list of tracks from this album.
Now I want to convert each Music object to a String without creating a new HashMap, is this
possible?
I've tried it with the Iterator scheme, for loop over the entry set and so on but nothing seems to work.
Edit://
My code for the convertmethod:
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet())
formatList.put(key, musiksammlung.get(key).toString());
return musiksammlung;
}
But this always results in an error "is not applicable for the Arguments (String, String) so I have no idea. Do I have to override toString()?
You're on the right path but you need to convert the existing List<Music> to a List<String> and put the List<String> into your new HashMap.
You also then want to return your newly created HashMap<String, List<String>> instead of your original one.
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet()) {
// Value to store in map
List<String> value = new ArrayList<String>();
// Get the List<Music>
List<Music> musicList = musiksammlung.get(key);
for (Music m: musicList) {
// Add String of each Music object to the List
value.add(m.toString);
}
// Add the value to your new map
formatList.put(key, value);
}
// Return the new map
return formatList;
}
So answer your question:
Now I want to convert each Music object to a String without creating a
new HashMap, is this possible?
You need to create a new HashMap, because it's storing different type of value: List<Music> is different from List<String>.
Also as mentioned in my previous answer, make sure you override Music.toString() so that it returns a meaningful String for you instead of the one it inherits from its parent classes, which includes at least java.lang.Object
formatList wants a List<String>, but musiksammlung.get(key).toString() returns a String (not a List<String>). Did you mean this?
HashMap<String, String> formatList = new HashMap<String, String>();
Have you tried something like this:
Iterator<String> it = musiksammlung.keySet().iterator();
while (it.hasNext()) {
List<Music> ml = musiksammlung.get(it.next());
for (Music m : ml)
System.out.println(m.toString());
}
And of course you should override the Music#toString() method with something you could use.
Try to change your HashMap like this:
private static HashMap<String, List<Object>> musiksammlung = new HashMap<String,List<Object>>();
So you can save any kind of objects in this HashMap. Also use instanceof to check the type of the object before using it.

Adding an Object to a collection

I am learning Hashmaps in Java, so I have a simple java program that creates an account. My problem is when it comes to storing the new accounts in a collection, I am trying to do it using a hashmap but just can't figure out where to go.
HashMap<String,CurrentAccount> m = new HashMap<String,String>();
if (Account.validateID(accountID)) {
CurrentAccount ca = new CurrentAccount(cl,accountID, sortCode, 0);
I am unsure of the next stage to add this account to the hashmap I have tried a couple of different ways but always end up with an error.
You have an error with your instantiation statement. The map's type is HashMap<String, CurrentAccount>, but you are instantiating HashMap<String,String>.
To fix this, change your instantiation statement to correspond to the map's type, like the following:
HashMap<String, CurrentAccount> m = new HashMap<String, CurrentAccount>();
Or if you are using JDK 1.7+, you could use diamond notation instead (see Generic Types for more information):
HashMap<String, CurrentAccount> m = new HashMap<>();
In order to add items to the map, you can use Map#put(K, V):
m.put(accountID, ca);
In order to get a value, you can use Map#get(Object):
CurrentAccount ca = m.get(accountID);
See JDK 1.7 Map documentation for more information about maps.
As for the question made by the OP in the comments of this answer, in order to access the map (or any other type) in multiple methods, it has to be declared as a class field:
public class TestClass {
Map<String, CurrentAccount> accountMap;
public TestClass() {
accountMap = new HashMap<String, CurrentAccount>();
}
public void method1() {
// You can access the map as accountMap
}
public void method2() {
// You can also acces it here
}
}
The map declaration is incorrect, as you're typing the value to two different objects. Change the declaration to:
Map<String,CurrentAccount> m = new HashMap<String,CurrentAccount>();
Then, presuming the accountID value is a string, it should be as simple as...
m.put( accountID, ca );
Altogether you'll have:
Map<String,CurrentAccount> m = new HashMap<String,CurrentAccount>();
if (Account.validateID(accountID)) {
CurrentAccount ca = new CurrentAccount(cl,accountID, sortCode, 0);
m.put( accountID, ca );
}
Use put(key, value); See HashMap javadoc
m.put("SomeIdentifierString", ca);
Then whenever you want to access that particular object. Use the key to obtain it
CurrentAccount account = m.get("SomeIdentifierString");
If you want to iterate through the entire map to get key and values you can do this
for (Map.Entry<String, CurrentAccount> entry : m.entrySet()){
String s = entry.getKey();
CurrentAccount accuont = entry.getValue();
// do something with them
}
Your code does not compile because you try to initialize the hasmap bound to the type String and Account to an hashmap of type String String for (key and value type)
HashMap<String, CurrentAccount> accountsMap = new Hashmap<String, String>()
should be
HashMap<String, CurrentAccount> accountsMap = new Hashmap<String, CurrentAccount>()
The first argument is the type for the key value the second is the type of the associated value for the key
To find a value within your hashmap you can use the following code snipped
for (String key : accountsMap.keySet().iterator()) {
CurrentAccount current = accounts.get(key);
}
where accountsMap is your HashMap.

Categories

Resources