How to get input from user for Hashmap using Scanner - java

How to get input from user for Hashmap using scanner and print the respective hashmap?
import java.util.HashMap;
import java.util.Scanner;
public class Map {
public static void main(String[] args) {
HashMap<Integer, Integer> hmap = new HashMap<>();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Integer a = in.nextInt();
Integer b = in.nextInt();
hmap.put(a, b);
System.out.println(hmap.put(a, b));
}
}
}
I am not getting the desired output. I want to print what is inserted in hmap.

Change your System.out.println statement to,
System.out.println(hmap.get(a));

This is another way to put data into a HashMap at runtime:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class MapDemo {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<>();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Integer a = in.nextInt();
String b = in.next();
hmap.put(a, b);
}
for (Map.Entry<Integer, String> m : hmap.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}

Javadoc for the HashMap util can be found here.
To add a key/value pair to a HashMap you use hashmap.put(x, y).
Using hashmap.get(x) at a later time will return y.
Edit: It looks like from other comments you are trying to have it print out both the key and the value. In the case that you are trying to print out all keys and values something like this may work.
hashMap.forEach((e, k) -> {
System.out.println("E: " + e + " K: " + k);
})
If this is not your intended purpose I would strongly recommend reading over the method summary section of the javadocs.

What do you expect this to do? It is wrong, why would you print hmap.put(a,b)
System.out.println(hmap.put(a,b));
Just take it out of the for loop and print it separately
for (Map.Entry<Integer, Integer> pair: hmap.entrySet()) {
System.out.println(pair.getKey() + "->" + pair.getValue());
}

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Call {
public static void main(String[] as) {
getData();
}
public static void getData() {
Map<Integer, String> hashmap = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Shashank Pathak\nEnter number of character: ");
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
Integer b = sc.nextInt();
String c = sc.nextLine();
hashmap.put(b, c);
}
for (Map.Entry<Integer, String> mp : hashmap.entrySet()) {
System.out.println("\n" + mp.getKey() + " " + mp.getValue());
}
}
}

I find this, And it is exactly the same as I want.
System.out.println("How many producs you want");
int listOfItem = sc.nextInt();
System.out.println("Type the product name and quantity you want to purchace and get the bill");
HashMap<Integer, String> products = new HashMap<>();
while(listOfItem-- >0){
products.put(sc.nextInt(),sc.nextLine());
}
System.out.println(products);
Output of above program

import java.util.*;
class hash1 {
void dic(){
HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
hmap.put(a,b);
System.out.println(hmap);
}
}
public class answer {
public static void main(String[] args) {
hash1 obj = new hash1();
for(int z = 0;z < 3;z++){
obj.dic();
}
}
}

Related

user input values are not added to hashmap

I have a hashmap which has pre entered values, and I am taking more values from the user. Then those values get sorted to the ascending order. But in this code user entered values not get inserted to the hashmap.
import java.sql.SQLOutput;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class CFG {
public static void main(String[] args) {
sortByValueJava8Stream();
}
private static void sortByValueJava8Stream()
{
Map<String, Integer> unSortedMap = getUnSortedMap();
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
System.out.println("Sorted Map : " + sortedMap);
}
public static Map<String, Integer> getUnSortedMap() {
Scanner in = new Scanner(System.in);
HashMap<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("Shiran", 342);
unsortMap.put("Hashini", 448);
unsortMap.put("Chanchala", 398);
unsortMap.put("Priyankara", 399);
unsortMap.put("Mayuri", 350);
unsortMap.put("Sameera", 321);
unsortMap.put("Supun", 299);
unsortMap.put("Supuni", 378);
unsortMap.put("Kavindu", 384);
unsortMap.put("Nadeeka", 440);
System.out.println("Do you want to add more players? ");
System.out.println("if yes pres 1 : ");
Integer c = in.nextInt();
if (c == 1) {
addUser();
} return unsortMap;
}
public static void addUser(){
Scanner in = new Scanner(System.in);
Map<String, Integer> unsortMap = new HashMap<>();
System.out.println("Enter name : ");
String a = in.nextLine();
in.nextLine();
System.out.println("Enter Time : ");
Integer b =in.nextInt();
unsortMap.put(a,b);
}
}
I have created a method called adduser() and I called it to add the new values. but data not get entered by it. How I can fix this ?
One way to do this is globally declaring unsortMap Map so that it can be used in other methods.
The issue is with your addUser method as it creates a local unsortMap which is never used after completion of the function.
Another way is to pass the unsortMap Map as a parameter to the addUser method and put the required pair.
Following is the modified working code.
class CFG
{
static Map<String, Integer> unsortMap; // global declaration of Map
public static void main(String[] args)
{
sortByValueJava8Stream();
}
private static void sortByValueJava8Stream()
{
Map<String, Integer>unSortedMap = getUnSortedMap();
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
System.out.println("Sorted Map : " + sortedMap);
}
public static Map<String, Integer> getUnSortedMap()
{
Scanner in = new Scanner(System.in);
unsortMap = new HashMap<>(); // Initializing the Map
unsortMap.put("Shiran", 342);unsortMap.put("Hashini", 448);
unsortMap.put("Chanchala", 398);unsortMap.put("Priyankara", 399);
unsortMap.put("Mayuri", 350);unsortMap.put("Sameera", 321);
unsortMap.put("Supun", 299);unsortMap.put("Supuni", 378);
unsortMap.put("Kavindu", 384);unsortMap.put("Nadeeka", 440);
System.out.println("Do you want to add more players? ");
System.out.println("if yes pres 1 : ");
Integer c = in.nextInt();
if (c == 1)
addUser();
return unsortMap;
}
public static void addUser()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter name : ");
String a = in.nextLine();
System.out.println("Enter Time : ");
int b = in.nextInt();
unsortMap.put(a,b);
}
}
You have to pass unSortedMap to addUser method.
public static Map<String, Integer> getUnSortedMap() {
Scanner in = new Scanner(System.in);
HashMap<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("Shiran", 342);
unsortMap.put("Hashini", 448);
unsortMap.put("Chanchala", 398);
unsortMap.put("Priyankara", 399);
unsortMap.put("Mayuri", 350);
unsortMap.put("Sameera", 321);
unsortMap.put("Supun", 299);
unsortMap.put("Supuni", 378);
unsortMap.put("Kavindu", 384);
unsortMap.put("Nadeeka", 440);
System.out.println("Do you want to add more players? ");
System.out.println("if yes pres 1 : ");
Integer c = in.nextInt();
if (c == 1) {
addUser(unsortMap);
} return unsortMap;
}
public static void addUser(Map<String, Integer> unsortMap){
Scanner in = new Scanner(System.in);
System.out.println("Enter name : ");
String a = in.nextLine();
in.nextLine();
System.out.println("Enter Time : ");
Integer b =in.nextInt();
unsortMap.put(a,b);
}

adding to Maps in Java

Hi i am trying to add countries to a map see below code. I am able to input the countries but my out is not what i expected. The Set prints out 4 times where i want each country counting form 1-4 not each Set. can you help?
/**
* MY CODE SO FAR = pleae can you help
*/
import java.util.*;
class EuroGroupStages {
public static void main(String args[]) {
Map<Integer, Set<String>> groupA;
Map<Integer, Set<String>> groupB;
Map<Integer, Set<String>> groupC;
Map<Integer, Set<String>> groupD;
//public EuroGroupStages()
// {
groupA = new TreeMap<>();
groupB = new TreeMap<>();
groupC = new TreeMap<>();
groupD = new TreeMap<>();
// }
//public void addCountries()
// {
Scanner keyboard = new Scanner(System.in);
Set<String> country = new HashSet<>();
String aCountry;
for(int i = 1; i < 5; i++)
{
System.out.print("Please enter a country");
aCountry = keyboard.next();
country.add(aCountry);
groupA.put(i, country);
}
System.out.println(groupA);
keyboard.close();
// }
}
}
{1=[England, Scotland, Czech, Croatia], 2=[England, Scotland, Czech, Croatia], 3=[England, Scotland, Czech, Croatia], 4=[England, Scotland, Czech, Croatia]}
Instead of System.out.println(groupA);
try to write:
for(int i = 1; i < 5; i++)
{
System.out.println(groupA.get(i));
}
for getting the value of each key in groupA.
Edit:
Here are some examples for getting the combinations of key+value:
(https://www.techiedelight.com/iterate-map-using-keyset-java/)
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Stream;
public class Main
{
// Program to iterate map using `keySet()` in Java
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.put(4, "Four");
// 1. Using an iterator
Iterator<Integer> itr = map.keySet().iterator();
while (itr.hasNext())
{
Integer key = itr.next();
String value = map.get(key);
System.out.println(key + "=" + value);
}
// 2. For-each loop
for (Integer key: map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
// 3. Java 8 - Iterator.forEachRemaining()
map.keySet()
.iterator()
.forEachRemaining(key -> System.out.println(key + "=" + map.get(key)));
// 4. Java 8 - Stream.forEach()
map.keySet().stream()
.forEach(key -> System.out.println(key + "=" + map.get(key)));
// 5. Java 8 - Stream.of() + toArray() + forEach()
Stream.of(map.keySet().toArray())
.forEach(key -> System.out.println(key + "=" + map.get(key)));
}
}
Code is compileable in java-online compiler:
(https://www.tutorialspoint.com/compile_java_online.php)
One of these approaches is certainly applicable to your code.
You're putting each country in a set and then adding the whole set each time. What I think you want to do is to put the countries in individual sets and add those to the map (more information would be helpful). To do this, a new Set must be created in each iteration of the loop to hold the next country.
// first you can delare you maps like this.
Map<Integer, Set<String>> groupA= new TreeMap<>();
Scanner keyboard = new Scanner(System.in);
for(int i = 1; i < 5; i++) {
System.out.print("Please enter a country");
Set<String> country = new HashSet<>();
country.add(keyboard.next());
groupA.put(i, country);
}
groupA.entrySet().forEach(System.out::println);
Prints something like
1=[USA]
2=[Canada]
3=[Norway]
4=[England]
And do not close the Scanner when taking input from the keyboard.

Collections which increase number of occurrences instead of adding duplicate

Does exist any collection which stores only unique strings, but count how many times this string was added?
So every time, when I try add the same string/item again, number of items remain the same but numbers of occurrence of given item will increase?
You can use a HashMap and wrap some code around it:
public class CounterMap<K> {
private final Map<K, Integer> internalMap = new HashMap<K, Integer>();
public void increment(K key) {
initKeyIfNew(key);
Integer oldValue = internalMap.get(key);
Integer newValue = oldValue + 1;
internalMap.put(key, newValue);
}
public int getCount(K key) {
initKeyIfNew(key);
return internalMap.get(key);
}
private void initKeyIfNew(K key) {
if (internalMap.get(key) == null) {
internalMap.put(key, 0);
}
}
}
Then you can use it like this:
CounterMap<String> myCounterMap = new CounterMap<String>();
myCounterMap.increment("hello");
...
As far as I know, there is not such build in collections, but you can simply achieve that by using Map collection:
Map<String, Integer> map = new HashMap<>();
String sample = "foo";
if (map.containsKey(sample))
map.put(sample, map.get(sample) + 1);
You can also use solution from external library, for example Multiset from Google Guava:
Multiset<String> multiset = HashMultiset.create();
String test = "foo";
multiset.add(test);
multiset.add(test);
multiset.add(test);
System.out.println(multiset.count(test));
with output:
3
Hope it helps.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class UniqueStringCount {
public static void main(String[] args) {
boolean takeUserInput = true;
HashMap<String, Integer> uniqueStringMap = new HashMap<>();
int counter = 0;
System.out.println("Welcome. To close the program type exit.");
System.out.println();
do {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the unique string");
String userInput = scan.next();
if(userInput.equalsIgnoreCase("exit")) {
takeUserInput = false;
scan.close();
}
System.out.println();
if(!userInput.equalsIgnoreCase("exit")) {
if(uniqueStringMap.containsKey(userInput)) {
counter = uniqueStringMap.get(userInput);
uniqueStringMap.put(userInput, ++counter);
continue;
}
counter = 0;
uniqueStringMap.put(userInput, ++counter);
}
} while(takeUserInput);
if(!uniqueStringMap.isEmpty()) {
for(Map.Entry<String, Integer> entry : uniqueStringMap.entrySet()) {
System.out.println("String " + entry.getKey() + " was added " + entry.getValue() + " times.");
System.out.println();
}
System.out.println("Bye bye.");
}
}
}
With Java 8:
Map<String, Integer> map = new HashMap<>();
When adding a string, do:
map.merge(s, 1, Integer::sum);
What this does is add the string s and set the value to 1 if it wasn't there yet. If it was there already, then it takes the current value and the new value you're adding (1 again) and sums them, and puts that back into the map.

Not printing occurrences of each keys correctly with the HashMap

I am trying to print how many times a particular Key has occurred in an array and it seems like it's printing one for all of the values. Could anyone please tell me what logical error I am having in the code below:
import java.util.HashMap;
import java.util.Map;
public class MostOccuranceOfNumber {
public static void main(String[] args) {
int[] n = {1,2,3,4,5,6,7,7,7,7};
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
// Create Hash Map
for(int i = 0 ; i < n.length ; i++){
if(map.containsKey(n)){
map.put(n[i], map.get(n[i]) +1);
}
else{
map.put(n[i], 1);
}
for(Map.Entry<Integer, Integer> m : map.entrySet()){
System.out.println("Key "+m.getKey()+"Occured"+m.getValue()+"times");
}
}
}
}
Try this:
import java.util.HashMap;
import java.util.Map;
public class MostOccuranceOfNumber {
public static void main(String[] args) {
int[] n = {1,2,3,4,5,6,7,7,7,7};
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
// Create Hash Map
for(int i = 0 ; i < n.length ; i++){
if(map.containsKey(n[i])){//you made mistake here
map.put(n[i], map.get(n[i]) +1);
}
else{
map.put(n[i], 1);
}
}
}
for(Map.Entry<Integer, Integer> m : map.entrySet()){
System.out.println("Key "+m.getKey()+"Occured "+m.getValue()+" times ");//Sorry forgot to take it outside
}
}

Exception in thread "main" java.lang.NullPointerException

I started to learn java yesterday and I wrote the followind program which should print pairs of equal numbers, but when I run it I get
Exception in thread "main" java.lang.NullPointerException
at _aaaa.main(_aaaa.java:26)
Here is my program:
import java.util.*;
class pair {
int first, second;
pair() {
first = second = 0;
}
public void make_pair(int a, int b)
{
first = a;
second = b;
}
}
public class aaaa {
public static void main(String[] idontneedthis)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt(), i, lg = 0;
int[] A = new int[5010];
pair[] B = new pair[5010];
for (N <<= 1, i = 1; i <= N; ++i)
{
int var = input.nextInt();
if (A[var] > 0)
{
B[++lg].make_pair(A[var], var);
A[var] = 0;
}
else
{
A[var] = i;
}
}
if (lg == 0) System.out.print("-1");
for (i = 1; i <= lg; ++i)
{
System.out.print(B[i].first + " " + B[i].second + "\n");
}
}
}
Please tell me what is wrong or why do I get this error. I mention that if I cut the line 26 ( B[++lg].make_pair(A[var], var); ) it will write -1.
Thank you!
You need to initialise the pairs in your array:
if (A[var] > 0) {
B[++lg] = new pair(); //here
B[lg].make_pair(A[var], var);
A[var] = 0;
}
This line:
pair[] B = new pair[5010];
creates an array of 5010 pairs but until you initialise them, they are all null.
Also note that since 5010 and N are not related, you could get an ArrayIndexOutOfBoundException depending on N.
This is how I would write it. The less said the better ;)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Pair {
final int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
#Override
public String toString() {
return first + " " + second;
}
}
public class Main {
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
int numOfPairs = input.nextInt();
List<Pair> pairs = new ArrayList<Pair>();
for(int i = 0; i < numOfPairs;i++) {
int first = input.nextInt();
int second = input.nextInt();
pairs.add(new Pair(first, second));
}
for (Pair pair : pairs)
System.out.println(pair);
}
}
pair[] B = new pair[5010];
Only allocates the space for 5010 B elements. You need to instantiate each element in that array.
for(int i = 0; i <B.length;i++)
{
B[i] = new pair();
}
Style things:
Class names start with upper case letters: AAAA not aaaa.
also star imports are bad:
import java.util.*;
replace with:
import java.util.Scanner;

Categories

Resources