Iterating over the map and calling another method - java

I am getting an map as shown below inside a method
Map<Integer, Integer> result1 =jmxService.generateMabc(p1, p2,p3,p4);
now the map result 1 will consists oif key value pair as usal
now i want to iterate over the map one by one , fetch the value of the map
that is both key and value which will be of type integer and convert them into string
and store the string two string variables like shown below
string j = will store the key
string t = will store the value
amd then pass these two parameters to another method call which wil take string
j and string t as parameter once they pass i want j and t to be null so that in next iteration the same process and can be continued till the time map has value c an you please advise how to achieve this, what I have tried is..
for (Map.Entry<Integer, Integer> entry : result1.entrySet())
{
String j, t;
j=entry.getKey();
t= entry.getValue();
abc .callanothermethod(string p1,stringp2, stringj, string t)
j=null;
t=null;
}
please advise what will be the correct appoach to obtain the same.

An Integer is not a String. So j = entry.getKey() doesn't make sense.
You need to transform the Integer into a String (by calling toString() for example):
j = entry.getKey().toString();
You really need to learn to
read the error messages from the compiler, which tell you waht is wrong and where
read the javadoc of the classes you're using, to understand what you can do with them.

Related

Foreach Key/Value pair issue

I'm trying to convert a PHP script into a Java one but coming across a few issues on a foreach loop. In the PHP script I have a foreach that takes the key:value pair and based off this does a str_replace.
foreach ($pValues AS $vKey => $vValue)
$vString = str_replace("{".$vKey."}", "'".$vValue."'", $vString);
I tried replicating this in Java without success. I need to get the key from the array to use in the string replace function, but can't find out where or if it's possible to get the key name from the array passed in.
Is this the right way or am I completely off? Should I be using the ImmutablePair method?
for (String vKey : pValues)
// String replace
Here's hoping there is an easy way to get the key:value pair in Java.
This can be acheived by using Map as data structure and then using entryset for iterating over it.
Map<K,V> entries= new HashMap<>();
for(Entry<K,V> entry : entries.entrySet()){
// you can get key by entry.getKey() and value by entry.getValue()
// or set new value by entry.setValue(V value)
}
That is not possible with a simple foreach-loop in Java.
If pValues is an array, you could use a simple for-loop:
for (int i = 0; i < pValues.length; i++)
// String replace
If pValues is a Map, you can iterate through it like this:
for (Key key : map.keySet())
string.replace(key, map.get(key));
Group Totals
Have the function GroupTotals(strArr) read in the strArr parameter containing key:value pairs where the key is a string and the value is an integer. Your program should return a string with new key:value pairs separated by a comma such that each key appears only once with the total values summed up.
For example: if strArr is ["B:-1", "A:1", "B:3", "A:5"] then your program should return the string A:6,B:2.
Your final output string should return the keys in alphabetical order. Exclude keys that have a value of 0 after being summed up.
Thanks all for the help and advice, I've managed to duplicate the function in Java using Map.
if (pValues != null)
{
Set vSet = pValues.entrySet();
Iterator vIt = vSet.iterator();
while(vIt.hasNext())
{
Map.Entry m =(Map.Entry)vIt.next();
vSQL = vSQL.replace("{" + (String)m.getKey() + "}", "'" + (String)m.getValue() + "'");
vSQL = vSQL.replace("[" + (String)m.getKey() +"]", (String)m.getValue());
}
}

Unsure how this piece of code is doing what it does… .getDescribe()

I'm relatively new to Apex and Java.
Could someone possibly explain this snippet of code?
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (String name : m.keySet()) {
DescribeFieldResult r = m.get(name).getDescribe();
System.debug(r);
}
I know it's getting the Describe information for each field on the Opportunity object, but could someone explain, line by line, how it's doing it?
Cheers!
This is about as basic as it gets when you need to enumerate a map:
Line 1 gets the map, and stores it in variable m
Line 2 iterates over the keys of the map m, using name variable for the value of the key in this iteration
Line 3 gets the item from the map m using name for the key, and calls getDescribe
Line 4 passes the result to System.debug
Line 5 closes the loop
However, this is not the best way of iterating the values, though: a simpler approach would be as follows:
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (SObjectField val : m.values()) {
System.debug(val.getDescribe());
}
For completeness, if you would like to iterate both keys and values, iterate entrySet, like this:
Map<String, SObjectField> m = Opportunity.SObjectType.getDescribe().fields.getMap();
for (Map.Entry<String,SObjectField> e : m.entrySet()) {
// e.getKey() produces the key
// e.getValue() produces its associated value
}
Iterating keys and then retrieving the values in a separate call to get is inefficient.

How to split next entryset iterator?

Hello I'm trying to split next iterator entryset from hashmap but I can't get it to work.
I have an hashmap in which I put two things, first one is sender, second one is channel:
channelList = HashMap()
channelList.put(playername, channelname) #have on mind that those can be changed, depending on what user types in
I have this iterator:
it = channelList.entrySet().iterator()
next = it.next()
But when I print next out it has "=" between arguments from hashmap. For example, if playername is PLAYER and channel name is balkan I get as result: PLAYER=balkan. Question is, how do I get ONLY PLAYERNAME on every next. I tried splitting it like this, but it's not working:
next = it.next()
realnext = next.split("=")
realrealnext = realnext.split("=")[0]
Have on mind that I check for every next using this while loop:
while it.hasNext():
Thanks in advance, Amar!
P.S. I'm jython/python programmer.
The problem is you're casting java.util.Map.Entry to a String. Try this instead
#!/usr/bin/jython
import java.util.HashMap
channelList = java.util.HashMap()
channelList.put("Hello", "World")
it = channelList.entrySet().iterator()
while (it.hasNext()):
e = it.next()
print("key = " + e.getKey())
print("value = " + e.getValue())
Which on my system runs as follows -
$ ./test.py
key = Hello
value = World
$
You shouldn't name reference to Map ....List, it is confusing. You should name it channelMap.
Next, your Maps should use generic types to set up elements they are using, like for example
Map<String, Channel> channelMap = new HashMap<>();
This way you would be able to safely use
Iterator<Entry<String, Channel>> it = channelMap.entrySet().iterator();
and have access to it.next().getKey() (notice that order of elements in HashMap is based on hashCode if its Key so don't be surprised with order like Player2, Player1, Player 3).
Anyway if you just want to iterate over all keys then maybe
for (String key: channelMap.keySet()){
System.out.println(key);
}
would be better solution.

How to check the content from a Map?

I have a Problem with a Map in Java.
The Code looks like this:
Map<Object, Object> test = myClass.getMap();
int value = (int) test.get(myID);
When I reach the second line I get a:
java.lang.NullPointerException
Now I'm asking myself how to debug this and find yout why this is not working? I'm quite sure that all keys and values are in this map.
How to print out the whole map so I can search if the key is available? (Its a very long map)
Or what is the right way to find the problem?
you can do map.containsKey(key) to check if the key exists
The reason for NPE, is that the value for myId in the map was null and you are trying to convert it to primitive int (which cannot hold non null values). Changing it to below statement will avoid the exception (unless the map test itself is null)
Integer value = (Integer ) test.get(myID);
Multiple problems here :
Map test could be null.
You cannot cast from Object to int. You need to cast it to Integer.
I believe the below line shouldn't compile:
int value = (int) test.get(myID);
as get() returns Object , and you are trying to cast it to primitive int. Even if you cast it to Integer :
int value = (Integer) test.get(myID); // assume auto-unwrapping here
The above code will throw NPE , if get(myID); is null.
You need to use :
Integer value = (Integer) test.get(myID);
You can use test.containsKey(myID) , to check for key. Finally do something like this :
if(test!=null && test.containsKey(myID))
Integer value = (Integer) test.get(myID);
You should use Generics in your Map though.
Use an IDE with an integrated debugger: put a breakpoint somewhere after the map was instantiated and after it was initialized and see effectively what's inside the map.
Well to answer you'r question if you want to print the map:
for (Entry<Object, Object> entry : test.entrySet()) {
System.out.println("Key:" + entry.getKey() + " Value:" + entry.getValue());
}
However the containsKey() method should be probably what you rather need.

Selective and Specific printing of hash Map key - value pairs

While writing test automation, i was required to leverage the api's provided by the developers and these api accepts HashMap as arguments. The test code involves calling several such api with hashmap as the parameter as shown below.
Map<String,String> testMap = new HashMap<String,String>();
setName()
{
testMap.put("firstName","James");
testMap.put("lastName","Bond");
String fullName=devApi1.submitMap(testMap);
testMap.put("realName",fullName);
}
setAddress()
{
testMap.put("city","London");
testMap.put("country","Britain");
testMap.put("studio","Hollywood");
testMap.put("firstName","");
testMap.put("person",myMap.get("realName"));
devApi2.submitMap(testMap);
}
However the requirement was to print the testMap in both setName and setAddress functions, but the map should print only those elements (key-value pairs) in alternate lines which are set in the respective function. I mean setName should print 2 elements in the Map which are set before submitMap api is invoked and similarly setAddress should print 5 elements which are set before submitMap is invoked.
setName Output must be:
The data used for firstName is James.
The data used for lastName is Bond
setAddress Output must be:
The data used for city is London.
The data used for country is Britain.
The data used for studio is Hollywood.
The data used for firstName is null.
The data used for person is James Bond
Any help, in order to acheive this?
I would probably write a helper function that would add items to the map and do the printing.
public static <K,V> void add(Map<K,V> map, K key, V value){
System.out.println(String.format("The data used for \"%s\" is \"%s\"", key, value));
map.put(key, value);
}
If you need to print different messages you could either use different helper functions or pass format string as an argument.
I would create a method which takes a comma separated list of keys as argument and print only them.
Something like:
public void printKeys(Map<String,String> map, String csKeys) {
for(String key: csKeys.split(",")){
if(map.conatinsKey(key)){
System.out.println("The data used for " + key + " is " + map.get(key) );
}
}
}
and you can invoke it like:
printKeys(testMap, "firstName,lastName");
printKeys(testMap, "city,country,studio");
You'd better create a copy of your testMap when you invoke the submitMap method, since you don't have a flag to indicate which key-value pairs should be printed.
You could do it like
Map<String, String> printObj = new HashMap<String, String>
setName()
{
testMap.put("firstName","James");
testMap.put("lastName","Bond");
String fullName=devApi1.submitMap(testMap);
printObj.addAll(testMap);
testMap.put("realName",fullName);
}
Then print the printObj instead of testMap.
From you comments on my earlier answer it seems you don't want the values put from one method to be displayed in the second one...
That can be done easily, just place:
testMap.clear();
in the beginning of every method.

Categories