Iterating MultiMap in Java - java

I have a multimap like below:
map = {config1=[abc, xyz], config2=[abc]}
Now I try to iterate it using the following piece of code
Iterator<Entry<String, Object>> itr = map.entrySet().iterator();
while(itr.hasNext()) {
Entry<String, Object> entry = itr.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
I am getting the output as:
Key = config1, Value = [abc, xyz]
Key = config2, Value = [abc]
but I need the output as:
Key = config1
Value = abc
Value = xyz
Key = config2
Value = abc
How can I achieve this?

I can suggest something like this
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
String[] arr1 = {"abc", "xyz"};
String[] arr2 = {"abc"};
map.put("config1", arr1);
map.put("config2", arr2);
Iterator<Map.Entry<String, Object>> itr = map.entrySet().iterator();
while(itr.hasNext()) {
Map.Entry<String, Object> entry = itr.next();
System.out.println("entry.getKey() = " + entry.getKey());
for (Object object: (Object[]) entry.getValue()) {
System.out.println("object = " + object);
}
}
}
Then output will look like
entry.getKey() = config2
object = abc
entry.getKey() = config1
object = abc
object = xyz
The key action this is casting String[] to Object[].

Related

How to foreach json or object data with java

I have a return from Web-Service like this :
Object result = envelope.getResponse();
AND the return is like this
[{"nom":"Nexus09","poste":"4319"},{"nom":"Nexus08","poste":"4312"},{"nom":"Nexus07","poste":"4306"}]
I need to foreach the result to get "nom" and "poste" for every {"nom":"Nexus09","poste":"4319"}
THX
Using http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar Jar,
public static void main(String[] args) {
String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";
JSONArray jsonArray = new JSONArray(input);
jsonArray.forEach(j->System.out.println(j.toString()));
}
To parse the nested JSONObject, It can be done like below,
public static void main(String[] args) {
String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";
JSONArray jsonArray = new JSONArray(input);
for(Object object:jsonArray) {
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject)object;
Set<String> keys =jsonObject.keySet();
for(String key:keys) {
System.out.println(key +" :: "+jsonObject.get(key));;
}
}
}
}
Here is the code to loop through an array of JSON and also get all key-value pairs.
This should work.
Hope it helps.
Code:
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
for(JSONObject json : result)
{
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
}

Want to assign only the first key and second key from the hashmap to Long variable xyzId1 and xyzId2

public static Map<Long, Map<String, String>> xyz1 = new HashMap<Long,
Map<String, String>>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Long, Map<String, String>> entry : xyz1.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " +
entry.getValue());
Long xyzId1 = entry.getKey();
Long xyzId2 = entry.getKey();
}
I want to add only the first and second key from the hashmap to the Long variables and want to skip the rest.

An argument that accepts any kind of Data Type

I have this code:
public static Map buildMap(Map map){
Map data = new HashMap();
Map mapStorage = new HashMap();
Set<Map.Entry<String, Class<?>>> entryset = map.entrySet();
for (Map.Entry<String, Class<?>> entry : entryset) {
String key = entry.getKey();
Class<?> val = entry.getValue();
if(key.contains("_")){
String mapName = key.substring(0, key.indexOf("_"));
String mapKey = key.substring(key.indexOf("_")+1, key.length());
Class<?> mapValue = val;
boolean mapFound = false;
Set<Map.Entry<String, Map>> entryset1 = mapStorage.entrySet();
for (Map.Entry<String, Map> entry1 : entryset1) {
String key1 = entry1.getKey();
Map val1 = entry1.getValue();
if(key1.equals(mapName)){
val1.put(mapKey, mapValue);
mapFound = true;
}
}
if(!mapFound){
Map m = new HashMap();
m.put(mapKey, mapValue);
mapStorage.put(mapName, m);
}
}else{
data.put(key, val);
}
}
Set<Map.Entry<String, Map>> entryset2 = mapStorage.entrySet();
for (Map.Entry<String, Map> entry2 : entryset2) {
String key = entry2.getKey();
Map val = entry2.getValue();
data.put(key, val);
}
return data;
}
Demo on how it works:
Map m = new HashMap();
m.put("objid","1234");
m.put("state","CURRENT");
m.put("tdno","789-09483");
m.put("rpu_objid","R3534");
m.put("rpu_state","PENDING");
m.put("realproperty_objid","RP8393");
m.put("realproperty_owner","Charles Lio");
m.put("realproperty_address","USA");
Map data = DataBuilder.buildMap(m);
System.out.println(data);
When you run the code above, the output should return a Map whose value is something like this:
{rpu={objid=R3534, state=PENDING}, realproperty={objid=RP8393, address=USA, owner=Charles Lio}, objid=1234, tdno=789-09483, state=CURRENT}
But unfortunately, it throws an error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Class
QUESTION: How to change the code so that it will accept ANY TYPE OF DATA TYPE?
Simply replace Class<?> with Object as next:
public static Map buildMap(Map map){
...
Set<Map.Entry<String, Object>> entryset = map.entrySet();
for (Map.Entry<String, Object> entry : entryset) {
String key = entry.getKey();
Object val = entry.getValue();
if(key.contains("_")){
String mapName = key.substring(0, key.indexOf("_"));
String mapKey = key.substring(key.indexOf("_")+1, key.length());
Object mapValue = val;
...
Use Object instead of class
Set<Map.Entry<String, Class<?>>> entryset = map.entrySet();
to
Set<Map.Entry<String, Object>> entryset = map.entrySet();
public static Map buildMap(Map<String, Object> map){
Map<String, Object> data = new HashMap<>();
Map<String, Map<String, Object>> mapStorage = new HashMap<>();
Set<Map.Entry<String, Object>> entryset = map.entrySet();
for (Map.Entry<String, Object> entry : entryset) {
String key = entry.getKey();
Object val = entry.getValue();
if(key.contains("_")){
String mapName = key.substring(0, key.indexOf("_"));
String mapKey = key.substring(key.indexOf("_")+1, key.length());
String mapValue = val;
boolean mapFound = false;
Set<Map.Entry<String, Map>> entryset1 = mapStorage.entrySet();
for (Map.Entry<String, Map> entry1 : entryset1) {
String key1 = entry1.getKey();
Map val1 = entry1.getValue();
if(key1.equals(mapName)){
val1.put(mapKey, mapValue);
mapFound = true;
}
}
if(!mapFound){
Map<String, Map<String, Object>> m = new HashMap<>();
m.put(mapKey, mapValue);
mapStorage.put(mapName, m);
}
}else{
data.put(key, val);
}
}
Set<Map.Entry<String, Map>> entryset2 = mapStorage.entrySet();
for (Map.Entry<String, Map> entry2 : entryset2) {
String key = entry2.getKey();
Map val = entry2.getValue();
data.put(key, val);
}
return data;
}

write key and values from map to a file

With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.

Displaying the contents of a Map over iterator

I am trying to display the map i have created using the Iterator.
The code I am using is:
private void displayMap(Map<String, MyGroup> dg) {
Iterator it = dg.entrySet().iterator(); //line 1
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove();
}
}
Class MyGroup and it has two fields in it, named id and name.
I want to display these two values against the pair.getValue().
The problem here is Line 1 never gets executed nor it throws any exception.
Please Help.
PS: I have tried every method on this link.
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
for (Map.Entry<String, MyGroup> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
using iterator
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
Iterator<Map.Entry<String, MyGroup>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, MyGroup> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For more iteration information see this link

Categories

Resources