How to iterate through List in a hashmap value - java

I have a HashMap with String as key and List as value.
Name of the HashMap is pageMap.
Say this pageMap has the following key and value:
key = order
value = [page1, page2, page3]
now I want to display in the following pattern:
order
page1
page2
page3
key2
value1
value2
value3
value4
Please tell me how do I do that?

import java.util.*;
import java.lang.*;
public class StringListMapExample {
public static String asTreeFormattedString(HashMap<String,List<String>> map) {
final StringBuilder builder = new StringBuilder();
for (String key : map.keySet()) {
builder.append(key + "\n");
for (String string : map.get(key)) {
builder.append("\t" + string + "\n");
}
}
return builder.toString();
}
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put("order", Arrays.asList(new String[]{"page1", "page2", "page3"}));
System.out.println(asTreeFormattedString(map));
}
}

Actually the solution is quite straightforward.
hashmap.get(key).iterator();
is an iterator for the list of the given key.
Why did you not try to figure it out yourself?

Iterate using iterator through all keys of hashmap using keyset()
{
print key
Iterate through value list using iterator
{
print each value
}
}

public String formatDictionary(Map<String, List<String>> map){
String output = '';
for (String key : map.keySet()){
output = output + key + "\n";
for (String value: map.get(s)){
output = output + "\t" + value + "\n";
return output
Which is pretty similar to Jeppi's answer, but using string concatenation which is one of my favorite things about Java. I haven't run any benchmarks, but my guess is that his would be a little faster, but mine would have less overhead.

Related

How to print a single Key-Value pair in a HashMap in java?

Is it possible to do so? If yes, what is the required syntax/method?
I tried it by using,
System.out.println(key+"="+HM.get(key));
but it prints it in this format,
key= value
whereas, I need
key=value
(Due to outputting format in HackerRank)
while(sc.hasNextLine())
{
String s=sc.nextLine();
if(a.containsKey(s))
{
System.out.println(s+"="+a.get(s));
}
else
System.out.println("Not found");
}
EDIT 1:
I saw the solution given, the person used the following code,
while(scan.hasNext()){
String s = scan.next();
Integer phoneNumber = phoneBook.get(s);
System.out.println(
(phoneNumber != null)
? s + "=" + phoneNumber
: "Not found"
);
}
Now, why does this not have white space in the answer?
The only visible change I see is that this person used an object instead of primitive data type.
Also,this person used int instead of string in accepting the phone number, I initially did the same but it gave me an InputMismatchException .
There is no avalilable method in https://docs.oracle.com/javase/7/docs/api/java/util/Map.html to get Entity from map if there is any key or value available. Try below code if it help :
if (map.containsKey(key)) {
Object value = map.get(key);
System.out.println("Key : " + key +" value :"+ value);
}
You can use entrySet() (see entrySet) to iterate over your map.
You will then have access to a Map Entry which contains the methods getValue() and getKey() to retreive both the value and the key of your mapped object.
entrySet() returns a Set, and Set extends Collection, which offers the stream() method, so you can use stream to loop over and process your entrySet :
map
.entrySet() // get a Set of Entries of your map
.stream() // get Set as Stream
.forEach( // loop over Set
entry -> // lambda as looping over set entries implicitly returns an Entry
System.out.println(
entry.getKey() // get the key
+ "="
+ entry.getValue() // get the value
);
If needed, you can add .filter() to process only elements that matches your conditions in your Stream.
Working example here
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
for (int i = 1 ; i < 10 ; i++) {
put("key"+i, "value"+i);
}
}
};
myMap.entrySet().stream().forEach(
entry -> System.out.println(entry.getKey() + "=" + entry.getValue())
);
}
}
Output :
key1=value1
key2=value2
key5=value5
key6=value6
key3=value3
key4=value4
key9=value9
key7=value7
key8=value8

Selecting best data structure

Name - Code (String)
A - 123
B - 123
C - 23
D - 123
E - 23
F - 23
G - 66
H - 66
What's the best data structure to represent this data. Names should be able to iterate easily.
Edit
Names are unique.
What's needed to be done is something like this.
Had doubts in using Hashmap that why I asked.
Code is a STRING
for( loop dataStructure names (lets say n)){
if(NAME.equals(n){
String code = dataStructure.get(n);
do somthing
}
}
If the names are unique, a HashMap woulrd be apropriate.
You can iterate over the keys with keys().
To iterate over the entries you can iterate over the entrySet().
See the JavaDoc of Map
If you need to perform a reverse lookup you could use the BiMap from Guava. (General a very good library)
Map entries example:
public final class MapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "123");
for (Map.Entry<String, String> mapEntry : map.entrySet()) {
if (mapEntry.getKey().equals("A")) {
final String code = mapEntry.getValue();
System.out.println("Your desired code: " + code);
}
}
}
}
But since NAME seems to be a constant, you could simple do String code = map.get(NAME)?
I thinks you are considering this:
public enum Code {
A("123"),
B("123"),
C("23"),
D("123"),
E("23"),
F("23"),
G("66"),
H("66");
final public String value;
Code(String value) {
this.value = value;
}
}
String h = Code.H.value;
for (Code code : Code.values()) {
System.out.printf("Name %s, code %s%n", code, code.value);
}
Sounds like a Map. Specifically, if the order of the names is important, you can use a TreeMap.
You can populate it with the put method, and then iterate over the entries (or just the keys, or just the values):
// Fill the map:
Map<String, String> map = new TreeMap<>();
map.put("A", "123");
map.put("B", "123");
// etc...
// Iterate over it:
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.pritnln ("Key: " + entry.getKey() + " value: " + entry.getValue());
}
EDIT:
If the order is not important, as noted in later edits to the OP, a HashMap would do just fine.
Note, however, that if you're looking for a specific key, like stated in the example in the OP, there's no point in looping over the keys - you just need to use get or containsKey:
String name = ...;
String code = map.get(name);
if (code != null) {
// do something...
}
I would suggest go for HashMap
The HashMap class uses a hashtable to implement the Map interface.
This allows the execution time of basic operations, such as get( )
and put( ), to remain constant even for large sets
HashMap are efficient for locating a value based on a key and
inserting and deleting values based on a key. The entries of a
HashMap are not ordered.
import java.util.HashMap;
import java.util.Set;
public class MyHashMapRead {
public static void main(String a[]){
HashMap<String, Integer> hm = new HashMap<String, Integer>();
//add key-value pair to hashmap
hm.put("A", "1");
hm.put("B", "2");
hm.put("C","3");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}

HashMap, return key and value as a list

I have an homework to do, so I have finished the script but the problem is with the values.
The main code is (I cannot change it due to homework) :
List<String> result = cw.getResult();
for (String wordRes : result) {
System.out.println(wordRes);
}
It have to return:
abc 2
def 2
ghi 1
I have no idea how to handle that.
Now only shows:
abc
def
ghi
I have no idea how to change this method getResult to return with the value of the hashmap as well without changing the first main code.
public List<String> getResult() {
List<String> keyList = new ArrayList<String>(list.keySet());
return keyList;
}
The hashmap is: {abc=2, def=2, ghi=1}
And list: Map<String, Integer> list = new HashMap<String, Integer>();
Please help me if you know any resolution.
I think that now that you have learned about keySet and valueSet, your next task is to learn about entrySet. That's a collection of Map.Entry<K,V> items, which are in turn composed of the key and the value.
That's precisely what you need to complete your task - simply iterate over the entrySet of your Map while adding a concatenation of the value and the key to your result list:
result.add(entry.getKey() + " " + entry.getValue());
Note that if you use a regular HashMap, the items in the result would not be arranged in any particular order.
You need to change this line:
List<String> keyList = new ArrayList<String>(list.keySet());
to:
//first create the new List
List<String> keyList = new List<String>();
//iterate through the map and insert the key + ' ' + value as text
foreach(string item in list.keySet())
{
keyList.add(item+' '+list[item]);
}
return keyList;
I haven't written java in a while so compiler errors might appear, but the idea should work
Well simplest way make an ArrayList and add as #dasblinkenlight said...
Iterator<?> it = list.entrySet().iterator();
while (it.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry maps = (Map.Entry) it.next();
lista.add(maps.getKey() + " " + maps.getValue());
}
}
public List<String> getResult() {
List<String> temp = lista;
return temp;
}
If you want to iterate over map entries in order of keys, use an ordered map:
Map<String, Integer> map = new TreeMap<String, Integer>();
Then add your entries, and to print:
for (Map.Entry<String, Ibteger> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}

compare & extract two Hashmap

I used Scanner to read through A.txt to generate A Hashmap,
also same method to read through B.txt to have B Hashmap.
These two hashmap have the "SOME" same key and would like to combine with each other.
If the key is are the same, print out "key, value1, value2".
Here is I have so far :
public static void main (String[] args) throws FileNotFoundException {
Scanner scanner1 = new Scanner(new File("score.txt"));
Map<String, String> tolerance = new HashMap<>();
Scanner scanner2 = new Scanner(new File("Count2.txt"));
Map<String, String> Pdegree = new HashMap<>();
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String Name = array[0];
String score = array[1];
tolerance.put(Name,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String Name2 = array2[0];
String degree = array2[1];
Pdegree.put(Name2,degree);
}
for(Map.Entry<String, String> entry : tolerance.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
for(Map.Entry<String, String> entry2 : Pdegree.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if(key==key2){
System.out.println(key2 + "\t" + value + "\t" + value2);
}
}
}
}
}
Neither results nor error messages would show.
My question is how to extract the same key with respective values from two maps. Thanks.
I found the answer by myself. It should be
if(key.equals(key2))
You may use map1.putAll(map2) to combine two maps;
Why not use Guava's multimap? I believe that if you use put all and it comes across two identical keys, it simply adds a second value to the key. Then you can print out all teh key value pairs. If it has identical key and identical value what it does is implementation dependent.
https://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html#put(K, V)

printing a hashmap of a key with multiple values

class hello {
string name;
int number;
}
class object {
public static void main(string args[]) {
HashMap hs = new HashMap();
hello c1 = new hello();
hello c2 = new hello();
hs.put("india",c1);
hs.put("america",c2);
}
}
how to print he key value pairs
key with multiple values how is it printed
Iterate Map or HashMap like this.
Map<String, Hello> map=new HashMap<>();
Set<Entry<String, Hello>> entries=map.entrySet();
for (Entry<String, Hello> entry : entries) {
String key=entry.getKey();
Hello hello=entry.getValue();
}
With Java 8:
map.forEach((key, value) -> System.out.println(key + ", " + value));
You need to iterate over hash map keys, then print the key with its value.
Example:
HashMap<String, hello> map = new HashMap<String, hello>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key + map.get(keu).toString); suppose you already override the toString method in your hello class
}
You can iterate using Entry Set too.
HashMap<String,hello> hs=new HashMap<String, hello>();
// Put values for hashMap.
for(Map.Entry<String, hello> printPairs: hs.entrySet()) {
System.out.print(printPairs.getKey()+" ---- ");
System.out.println(printPairs.getValue());
}

Categories