Displaying the contents of a Map over iterator - java

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

Related

If I have two keys with equal value, how do I return a Set<String> kinda (value + " - " + key ", " + key)?

This code works only when I have a pair like name(value) + number(key), but I'm stuck with situation like - name + number, number. It returns name + number1, name + number2
public Set<String> getAllContacts() {
TreeSet<String> contacts = new TreeSet<>();
if (phoneBook.isEmpty()) {
return new TreeSet<>();
} else {
for (Map.Entry<String, String> entry : phoneBook.entrySet()) {
contacts.add(entry.getValue() + " - " + entry.getKey());
}
}
return contacts;
}
Basically you want to invert key and value of your phoneBook map. Since one name can have multiple numbers according to your example the output structure should be Map<String, List<String>>. With this name oriented phone book you can easily create your contact collection. E.g.
Map<String, List<String>> phoneBookByName = new HashMap<>();
phoneBook.forEach((k, v) -> {
List<String> numbers = phoneBookByName.computeIfAbsent(k, s -> new ArrayList<>());
numbers.add(v);
});
TreeSet<String> contacts = new TreeSet<>();
phoneBookByName.forEach((k, v) -> contacts.add(k + " - " + String.join(", ", v)));
return contacts;
or using streams
Map<String, List<String>> phoneBookByName = phoneBook.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
return phoneBookByName.entrySet().stream()
.map(entry -> entry.getKey() + " - " + String.join(", ", entry.getValue()))
.collect(Collectors.toCollection(TreeSet::new));

Iterating MultiMap in 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[].

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.

how to convert a hash table in string in java

I'm new in java and i want to convert a hash table in the form of a string, with each pair separated by any special character. I'm little confuse how to apply loop on the hash table and extract values from. Please explain me how to do this. Thanks in advance
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
foreach(){
hashstring += key + "=" + hashtable[key] + "|";
}
return hashstring;
}
You can use Map.Entry as follows:
String hashstring= "";
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
String seperator = "|";
StringBuilder sb = new StringBuilder();
Set<String> keys = detailHashtable.keySet();
for(String key: keys) {
sb.append(key+"="+detailHashtable.get(key)+ seperator);
}
return sb.toString();
Both the HashMap and HashTable can use Map.Entry to get both key and value simultaneously.
String hashstring= "";
for (Map.Entry<String, String> entry : detailHashtable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
Refer the API to know what operations can be used.
http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#entrySet()
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
for(Entry<String,String> entry : detailHashtable.entrySet()){
hashstring += entry.getKey() + "=" + entry.getValue() + "| ";
}
return hashstring;
}
Map from which Hashtable extends provides the method Map.entrySet(), which returns a set containing all entries in the map.
for(Map.Entry e : detailHashTable.entrySet()){
Object key = e.getKey();
Object value = e.getValue();
...
}
use entry.getKey().to String() and entry.getValue().toString();

How do I iterate through nested TreeMaps?

I have a set of 3 nested TreeMaps:
TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> keyDay = new TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>>();
TreeMap<Court, TreeMap<Time, String>> keyCourt = new TreeMap<Court, TreeMap<Time, String>>();
TreeMap<Time, String> keyTime = new TreeMap<Time, String>();
which store info for bookings. I'm trying to iterate through them using nested while loops to show all the bookings that have been created, but I need a way in the nested whiles to show only the values which relate to the relevant parent.
Here's what I have:
Iterator listOfDays = keyDay.keySet().iterator();
Iterator listOfCourts = keyCourt.keySet().iterator();
Iterator listOfTimes = keyTime.keySet().iterator();
String output;
while (listOfDays.hasNext()) {
DayOfWeek currentDay = (DayOfWeek) (listOfDays.next());
output += currentDay.toString() + "\n----------\n";
while (listOfCourts.hasNext()){
Court currentCourt = (Court) (listOfCourts.next());
output += currentCourt.toString() + ":\n";
while (listOfTimes.hasNext()){
Time currentTime = (Time) (listOfTimes.next());
String currentName = (String) keyTime.get(currentTime);
output += currentTime.toString() + " - " + currentName + "\n";
}
}
...but as expected (but not wanted), it just iterates through all the entries in each TreeMap til the end.
Can anyone help?
It's not very clear (what are listOfDays, listOfCourts and listOfTimes?), but I guess you need something like this:
for (Map.Entry<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> dayEntry : keyDay.entrySet()) {
DayOfWeek currentDay = dayEntry.getKey();
output += currentDay.toString() + "\n----------\n";
for (Map.Entry<Court, TreeMap<Time, String>> courtEntry : dayEntry.getValue().entrySet()) {
Court currentCourt = courtEntry.getKey();
output += currentCourt.toString() + ":\n";
for (Map.Entry<Time, String> timeEntry : currentCourt.getValue().entrySet()) {
Time currentTime = timeEntry.getKey();
String currentName = timeEntry.getValue();
output += currentTime.toString() + " - " + currentName + "\n";
}
}
}
In short, a map can be viewed as a set of map entries, and you can iterate through this entry set. Each entry has a key and a value. Since the value, in your case, is another map, you can repeat this operation on the value.

Categories

Resources