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);
}
Related
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.
This Aim of this program is to return the key in a map having maximum value.
This code works fine in Eclipse.
But returns these run time errors in my college's online ide for exams.
I tried my best guys.to sort this out...But i Can't.
can i anyone figure out what is the problem with this?
import java.util.*;
import java.util.Map.Entry;
class Main{
public static void main(String args[])throws Exception{
Scanner s = new Scanner(System.in);
Scanner e = new Scanner(System.in);
HashMap<String,Double> hm=new HashMap<String,Double>();
System.out.println("Enter the number of students ");
int n=s.nextInt();
s.nextLine();
String[] name= new String[n];
Double[] mark= new Double[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the details of the student "+(i+1));
name[i]=s.nextLine();
if(e.hasNext())
mark[i]=e.nextDouble();
hm.put(name[i],mark[i]);
}
String maxKey = getMaxEntry(hm).getKey();
System.out.println(maxKey);
}
public static Entry<String, Double> getMaxEntry(Map<String, Double> map){
Entry<String, Double> maxEntry = null;
Double max = Collections.max(map.values());
for(Entry<String, Double> entry : map.entrySet()) {
Double value = entry.getValue();
if(null != value && max == value) {
maxEntry = entry;
}
}
return maxEntry;
}
}
Exception in thread "main" java.lang.NullPointerException at
java.util.Collections.max(Collections.java:702) at
Main.getMaxEntry(Main.java:32) at Main.main(Main.java:26)
The following does not compare doubles, but objects:
max == value
It should be
value.equals(max);
As Double is the Object wrapper of a numeric type double.
And max might be null on an empty collection.
I make program like a marks journal. I am stuck in at users input. I want to make method which takes users input and puts it in HashMap. I guess there is a problem in my understanding methods works with each other.
import java.io.*;
import java.util.*;
public class Main {
HashMap marks;
public void scanMark(){
Scanner scan = new Scanner(System.in);
System.out.println("Class Mark");
String classname = scan.next();
int mark = scan.nextInt();
marks.put(classname, mark);
scan.close();
}
public static void main(String[] args) {
HashMap<String, Integer> markList = new HashMap<>();
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if(x == 1){
markList.scanMark();
}
}
}
scanMark is a method of the class Main, so you just can not do this:
markList.scanMark();
because markList is a HashMap object and has no method scanMark
so you can create an instance of the Main class and on that object call the method scanMark
public static void main(String[] args) {
Main mApp = new Main();
HashMap<String, Integer> markList = new HashMap<>();
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if (x == 1) {
mApp.scanMark();
}
}
You can't call the scanMark method on your HashMap since HashMap does not have that method. The scanMark method is located inside your Main class, so you need to call the scanMark method on an instance of Main. So your main will look like the following:
public static void main(String[] args) {
HashMap<String, Integer> markList = new HashMap<>();
` `Main main = new Main(); //create an instance of Main
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if(x == 1){
main.scanMark(); //call scanMark on Main object
}
}
I did several changes in your code. It is working now ;)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* #author pakOverflow
*/
public class Main
{
/** Constant - ADD MARK */
private static final String ADD_MARK = "Add Mark" ;
/** Constant - DELETE MARK */
private static final String DELETE_MARK = "Delete Mark" ;
/** Constant - SHOW MARK */
private static final String SHOW_MARK = "Show Mark" ;
/** Hash Map */
private Map<String, Integer> marks ;
private Main()
{
this.marks = new HashMap<String, Integer>() ;
}
public void scanMark()
{
Scanner scan = new Scanner(System.in) ;
final int itemNumber = scan.nextInt() ;
System.out.println("Item Number: " + itemNumber) ;
String classname = null ;
switch (itemNumber)
{
case 1:
classname = ADD_MARK ;
break ;
case 2:
classname = DELETE_MARK ;
break ;
case 3:
classname = SHOW_MARK ;
break ;
default:
classname = "Not found" ;
}
this.marks.put(classname, Integer.valueOf(itemNumber)) ;
System.out.println(this.marks);
scan.close() ;
}
public static void main(String[] args)
{
Main main = new Main() ;
System.out.println("1." + ADD_MARK + "\n2." + DELETE_MARK + "\n3." + SHOW_MARK);
main.scanMark() ;
}
}
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();
}
}
}
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.