How do I print out all keys in hashmap? [duplicate] - java

This question already has answers here:
Printing HashMap In Java
(17 answers)
Closed 8 years ago.
I'm trying to learn how hashmaps work and I've been fiddling with a small phonebook program.
But I'm stumped at what to do when I want to print out all the keys.
here's my code:
import java.util.HashMap;
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester(){
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number){
phoneBook.put(name, number);
}
public void printAll(){
//This is where I want to print all. I've been trying with iterator and foreach, but I can't get em to work
}
public void lookUpNumber(String name){
System.out.println(phoneBook.get(name));
}
}

Here we go:
System.out.println(phoneBook.keySet());
This will printout the set of keys in your Map using Set.toString() method. for example :
["a","b"]

You need to get the keySet from your hashMap and iterate it using e.g. a foreach loop. This way you're getting the keys which can then be used to get the values out of the map.
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester()
{
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number)
{
phoneBook.put(name, number);
}
public void printAll()
{
for (String variableName : phoneBook.keySet())
{
String variableKey = variableName;
String variableValue = phoneBook.get(variableName);
System.out.println("Name: " + variableKey);
System.out.println("Number: " + variableValue);
}
}
public void lookUpNumber(String name)
{
System.out.println(phoneBook.get(name));
}
public static void main(String[] args)
{
MapTester tester = new MapTester();
tester.enterNumber("A name", "A number");
tester.enterNumber("Another name", "Another number");
tester.printAll();
}
}

Maps have a method called KeySet with all the keys.
Set<K> keySet();

Related

Access treemap in another class and loop through the items

Here's my first Java class, which includes the TreeMap that I want to loop through:
package myFunctions;
import java.util.TreeMap;
public class myUrls {
public void main() {
TreeMap<String, String> getUrl = new TreeMap<String, String>();
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
// Print keys and values
for (String i : getUrl.keySet()) {
System.out.println("app name: " + i + " url: " + getUrl.get(i));
}
}
}
Here's my second class, where I want to take the previously mentioned TreeMap and loop through it:
package myFunctions;
public anotherClass() {
DA_devurl myUrls = new DA_devurl();
//Loop through the array and perform seperate actions for each keyvalue pair
}
In your first class, I recommend making your TreeMap a private instance variable with a getter method:
package functions;
import java.util.TreeMap;
public class MyUrls {
private TreeMap<String, String> getUrl;
public MyUrls() {
getUrl = new TreeMap<String, String>();
}
public void main() {
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
public TreeMap<String, String> getGetUrl() {
return this.getUrl;
}
}
Now, in your second class, all you need to do is call the getter method after creating an instance of your previous class, and then looping through its entries with the proper syntax:
package functions;
import java.util.TreeMap;
import java.util.Map;
public class AnotherClass {
public static void main(String args[]) {
MyUrls myUrl = new MyUrls();
// populates the TreeMap
myUrl.main();
TreeMap<String, String> urls = myUrl.getGetUrls();
// Loop through the array and perform seperate actions for each keyvalue pair
for (Map.Entry<String, String> entry : urls.entrySet()) {
// do something with entry.getKey() and entry.getValue()
}
}
}

JAVA Dictionary as parameter [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
Now I got a dictionary like this
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
dict.put("addr", item.getFinalAddr());
dict.put("receiver", item.getReceiverName());
dict.put("phone", item.getReceiverPhone());
and I'm going to pass this dictionary to funcion Test() as a parameter, what should I put in the '()'
public static int Test(Dictionary)
Is this correct? Thanks!
In your code you have to call this method:
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
// CAll THIS METHOD
Test(dict);
And in your method you can get this data:
// YOUR METHOD, where "dict" is passed argument/parameter
public static int Test(Dictionary dict) {
}
Its working here
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class Dict {
public static void main(String[] args) {
Dictionary<String, String> obj = new Hashtable<String, String>();
obj.put("Hello", "World");
obj.put("Hello1", "World3");
obj.put("Hello2", "World32");
Dict ca = new Dict();
ca.test(obj);
}
public void test(Dictionary<String, String> obj) {
Enumeration<String> enumData = obj.elements();
while (enumData.hasMoreElements()) {
System.out.println(enumData.nextElement());
}
}
}

Pushing the resultset data onto a nested hashmap with a List

I'm trying to push my resultset data onto a nested map. Honestly, I've been struggling with the logic of how to do it. Here's a sample of my resultset data,
ID Main Sub
1 Root Carrots
2 Root Beets
3 Root Turnips
4 Leafy Spinach
5 Leafy Celery
6 Fruits Apples
7 Fruits Oranges
I created a hashmap HashMap<Integer, HashMap<String, List<String>>>, in which I thought the innermap could hold the main col as key and the corresponding subs as the list of values. The outermap would contain the id as the key and the corresponding map as the value. I'm struggling to achieve this.
Any help would be appreciated.
I would suggest using a different structure.
You have unique Id's and sub, but your Main can be duplicate.
Thus I would suggest using the following structure:
HashMap>
where POJO has ID and sub.
the key of map would be main.
Thus you can easily do:
if (map.get(main)==null){
List<POJO> pojoList= new List<>();
pojolist.add(pojo);
}else{
List<POJO> pojoList=map.get(main);
pojoList.add(pojo);
}
But it ultimately depends if you need to do lookup using ID or main.
Below is the answer to your question. But the question is probably wrong. Since the ID is unique (just a guess) you're probably looking for
Map<Integer, DataObject> map = new HashMap<>();
where DataObject is a POJO containing the variabels main and sub. Adding data to such a structure is easy.
Answer to question (added to show you how Maps and Lists work):
private Map<Integer, Map<String, List<String>>> map = new HashMap<>();
public static void main(String[] args) {
new Tester().go();
}
private void go() {
add(1, "Root", "Carrots");
add(2, "Root", "Beets");
add(3, "Root", "Turnips");
add(4, "Leafy", "Spinach");
add(5, "Leafy", "Celery");
add(6, "Fruits", "Apples");
add(7, "Fruits", "Oranges");
}
private void add(int id, String main, String sub) {
if (!map.containsKey(id)) {
map.put(id, new HashMap<String, List<String>>());
}
ArrayList<String> list = new ArrayList<String>();
list.add(sub);
map.get(id).put(main, list);
}
There is no need to make nested hash maps because each row in the example is unique (each List in nested map will have only one value).
In any case here is algorithm example in Java 8 style for your particular need :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<ResultSet> rows = new ArrayList<>();
rows.add(new ResultSet().setId(1).setMain("Root").setSub("Carrots"));
rows.add(new ResultSet().setId(2).setMain("Root").setSub("Beets"));
rows.add(new ResultSet().setId(3).setMain("Root").setSub("Turnips"));
rows.add(new ResultSet().setId(4).setMain("Leafy").setSub("Spinach"));
rows.add(new ResultSet().setId(5).setMain("Leafy").setSub("Celery"));
rows.add(new ResultSet().setId(6).setMain("Fruits").setSub("Apples"));
rows.add(new ResultSet().setId(7).setMain("Fruits").setSub("Oranges"));
HashMap<Integer, HashMap<String, List<String>>> result = new HashMap<>();
rows.forEach(row -> {
HashMap<String, List<String>> subsByMain = result.getOrDefault(row.getId(), new HashMap<>());
List<String> subs = subsByMain.getOrDefault(row.getMain(), new ArrayList<>());
subs.add(row.getSub());
subsByMain.put(row.getMain(), subs);
result.put(row.getId(), subsByMain);
});
}
static class ResultSet {
private Integer id;
private String main;
private String sub;
Integer getId() {
return id;
}
ResultSet setId(Integer id) {
this.id = id;
return this;
}
String getMain() {
return main;
}
ResultSet setMain(String main) {
this.main = main;
return this;
}
String getSub() {
return sub;
}
ResultSet setSub(String sub) {
this.sub = sub;
return this;
}
}
}

How can i retrieve the key based on the value present in the multimap?

i have some keys which are pointing to many values in a multimap. how can i retrieve the key basing on the value present in the multimap. Here is my code.
package com.manoj;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class GuavaMap
{
public static void main(String[] args)
{
Multimap regions = ArrayListMultimap.create();
regions.put("asia", "afganistan");
regions.put("asia", "bangladesh");
regions.put("asia", "inida");
regions.put("asia", "japan");
regions.put("asia", "burma");
regions.put("europe", "andorra");
regions.put("europe", "austria");
regions.put("europe", "belgium");
regions.put("europe", "cyprus");
regions.put("oceania","australia");
regions.put("oceania", "fiji");
regions.put("oceania", "nauru");
Set<String> keys = regions.keySet();
System.out.println("key\t\t\t"+"values\t\t\t");
System.out.println();
String comp = null;
for(String key : keys)
{
System.out.print(key);
System.out.println(regions.get(key));
}
}
}
the above code is providing me the output as follows
i need the region name basing on the country.
Example: if i give "australia" output should be "oceania"
you can invert it
Multimap<String, String> invregions = Multimaps.invertFrom(regions , ArrayListMultimap.<String, String>create());
and call get("yourcountry");
this will give you the keys containing your country
Firstly, I would like to suggest to not use raw types and explicitly mention Key and Value type while creating Map.
Regarding your question to retrieve key depending on value, you can iterate over all entries of the map to do the same like:
class GuavaMap
{
//Explicitly mentioned key and value both are Strings here
public static Multimap<String, String> regions = ArrayListMultimap.<String, String>create();
public static void main(String[] args)
{
regions.put("asia", "afganistan");
regions.put("asia", "bangladesh");
regions.put("asia", "inida");
regions.put("asia", "japan");
regions.put("asia", "burma");
regions.put("europe", "andorra");
regions.put("europe", "austria");
regions.put("europe", "belgium");
regions.put("europe", "cyprus");
regions.put("oceania","australia");
regions.put("oceania", "fiji");
regions.put("oceania", "nauru");
Set<String> keys = regions.keySet();
System.out.println("key\t\t\t"+"values\t\t\t");
System.out.println();
String comp = null;
for(String key : keys)
{
System.out.print(key);
System.out.println(regions.get(key));
}
//usage of below defined method
String region = getRegion("australia");
System.out.println("Region for australia:" + region);
}
// Function to get the region name i.e. key
public static String getRegion(String country){
for(Entry<String, String> entry : regions.entries()){
if(entry.getValue().equals(country))
return entry.getKey();
}
return "Not found";
}
}
Thanks for the reply.
i found a solution based on the list, map and hashmap
package com.manoj;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class NestedList
{
public static void main(String[] args)
{
List asia = Arrays.asList("afganistan","japan","india","pakistan","singapore","sri lanka");
List europe = Arrays.asList("albania","belarus","iceland","russia","norway","turkey");
List middleEast = Arrays.asList("australia","new zealand","samoa","tonga","vanuatu");
Map region = new HashMap<>();
region.put("asia",asia);
region.put("europe", europe);
region.put("middleeast" ,middleEast);
String reg = null;
String val = null;
for(Object key : region.keySet())
{
reg = key.toString();
Iterator it = ((List) region.get(key)).iterator();
while(it.hasNext())
{
val = it.next().toString();
if(val.equalsIgnoreCase("india"))//here you have to provide the country name
{
System.out.println(reg);
}
}
}
}
}

Need help with HashMaps?

I have a following scenario:
public class MapTest {
String name = "guru";
/**
* #param args
*/
public static void main(String[] args) {
MapTest mapTest = new MapTest();
Map map = new HashMap();
map.put("name", mapTest.name);
System.out.println(mapTest.name);
map.put("name", "raj");
System.out.println(mapTest.name);
}
}
output is:
guru
guru
is there any way that I can get the output as
guru
raj
ie. I want the HashMap map and the member variable name to in sync.
Thanks.
You can't do that. That's not the way Java works. When you write:
map.put("name", mapTest.name);
that's putting the current value of mapTest.name into the map. After the argument has been evaluated, it's completely independent of the original expression.
If you need to do something like this, you would have some sort of mutable wrapper class - you'd put a reference to the wrapper into the map, and then you can change the value within the wrapper, and it doesn't matter how you get to the wrapper, you'll still see the change.
Sample code:
import java.util.*;
class StringWrapper {
private String value;
StringWrapper(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return value;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Map<String, StringWrapper> map = new HashMap<String, StringWrapper>();
StringWrapper wrapper = new StringWrapper("Original");
map.put("foo", wrapper);
System.out.println(map.get("foo"));
wrapper.setValue("Changed");
System.out.println(map.get("foo"));
}
}
You appear to be confused about how maps work. For a better idea, try printing out the map.
map.put("name", mapTest.name);
System.out.println(map);
map.put("name", "raj");
System.out.println(map);
You will get:
{"name"="guru"}
{"name"="raj"}
Note that mapTest.name == "guru" always as you never modify it.
Java maps just don't support anything like this. When you do
map.put("name", mapTest.name);
You put a reference to the object referenced by mapTest.name in the map. When you do
map.put("name", "raj");
You put a reference to the new String object in the map. The reference to mapTest.name isn't in the map anymore.
Out of curiosity, why don't you want to just use map.get("name")?
If you want something to be performed dynamically, you should use a function/method.
public class MapTest {
private final Map<String, String> map = new HashMap<String, String>();
public String name() {
return map.get("name");
}
public static void main(String[] args) {
MapTest mapTest = new MapTest();
mapTest.map.put("name", "guru");
System.out.println(mapTest.name());
mapTest.map.put("name", "raj");
System.out.println(mapTest.name());
}
}
prints
guru
raj

Categories