I have a question about Maps, from the type Integer,Integer. I made a mistake by solving a problem based on <Integer,Integer> map on <String,String>, the end result was correct however, the order of numbers was not descending. That would be solved if I chose Integer instead of Strings.
How can I take the input from the user and assign it to keys/values of my map when it is Map<Integer, Integer>? I used substring() and indexOf() to make my old map but for integers I couldn't find a way
import java.util.*;
import java.io.*;
import type.lib.*;
public class MapTesting {
public static void main(String[] args) {
PrintStream output = new PrintStream(System.out);
Scanner input = new Scanner(System.in);
Map<String,String> normal = new HashMap<String,String>();
output.println("Enter your map, one key-value pair per line,");
output.println("comma-separated. Use empty line as sentinel.");
for ( String entry = input.nextLine(); entry.length() !=0;
entry = input.nextLine()) {
int comma = entry.indexOf(",");
String key = entry.substring(0,comma);
String value = entry.substring(comma+1);
normal.put(key,value);
}
output.println("The input map is:");
output.println(normal);
Map<String,String> reverse = new HashMap<String,String>();
boolean distinct = true;
for (Map.Entry<String,String> entry : normal.entrySet()) {
String keyY = entry.getKey();
String valueE = entry.getValue();
String existingReverseValue = reverse.get(valueE);
if (existingReverseValue != null) {
int currentValue = Integer.parseInt(existingReverseValue);
int potentialNewValue = Integer.parseInt(keyY);
if ( potentialNewValue < currentValue) {
reverse.put(valueE,keyY);
}
} else {
reverse.put(valueE,keyY);
}
}
output.println("The inverted map [using the smaller key as a tie breaker]:");
output.println(reverse);
}
}
int keyInt = Integer.valueOf(key)will get the integer of the number represented by the String.Stringor per singlebyte. If you readbytebybyte, then good luck. If you readStringbyString, then you will need to convertStringintoInteger, and use thisIntegerhowever you want/need, which in this case seems to be the key and value for yourMap.