My assignment is to write code that swaps the keys for the values of a map (with non 1:1) ratio, and I thought to create a TreeMap. So far I have:
public static Map<String, Set<String>> reverseMapping(Map<String, String> mapping) {
TreeMap <String, String> temp = (TreeMap<String, String>) mapping;
while (temp.pollFirstEntry() !=null ){
Map.Entry<String, String> iter=temp.pollFirstEntry();
String newKey = iter.get(iter.firstKey());
}
but it's saying that first.Key() is undefined for map.entry and suggests I cast iter. but that just makes things worse.
How can I achieve my goal of breaking the map entry down into its keys and values in a new set and string, respectively? Is this possible using the starting point I have, or at all?
As per your comments, what you want to know is how to iterate over each entries of a map.
Let me explain you how with a simple snippet :
for(Map.Entry<String, String> entry : temp.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
}
I'm pretty sure you can solve your issue now.
This will give you the reverse of a map.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
TreeMap<String, String> tm1 =new TreeMap<String, String>();
tm1.put("Hello" , "Me");
tm1.put("Bye", "Jim");
TreeMap<String , String > reverse = reverse(tm1);
System.out.println(reverse);
}
public static TreeMap<String , String > reverse(TreeMap<String, String> tm1){
TreeMap<String , String > reverse =new TreeMap<String, String>();
for(String s : tm1.keySet())
{
String v= tm1.get(s);
reverse.put(v,s);
}
return reverse;
}
}
Related
I need help on update the values while iterating Hash Map object.
Suppose , I have one Hash Map object like this ,
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("X", "D10023A");
hashMap.put("DATE", "5/1/2020");
hashMap.put("Y", "");
hashMap.put("Z", "");
hashMap.put("A", "");
I need to iterate over this Hash Map object, while iterating we need to check the condition i.e if Key=DATE and it's value = "5/1/2020", then need to update/set other key's i.e Y,Z,A values are, from empty("") strings to some integer values.
Please help me here.
Map.Entry has backward connection to the Map instance. I.e. when you modify an Entry, Map is modified as well.
public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<>();
map.put("X", "D10023A");
map.put("DATE", "5/1/2020");
map.put("Y", "");
map.put("Z", "");
map.put("A", "");
if ("5/1/2020".equals(map.get("DATE"))) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if ("DATE".equals(entry.getKey()))
continue;
if ("".equals(entry.getValue()))
entry.setValue("666");
}
}
}
I have a nested HashMap:
HashMap<String, Map<String,Integer>> map = new HashMap<>();
The key for the nested map may have multiple values:
{Color={Red=4, Blue=6}}
I want to be able to return the key of the nested map that has the lowest value. In this case, if I gave the key Color from the outer map, I want to have Red returned.
Any help is greatly appreciated.
Get the inner map by key.
Get the Iterator of the inner map.
Assign the first kvp as the minimum.
Loop through the iterator checking if any subsequent kvp is less than the minimum and assign it if true.
Return the minimum's key.
Code Sample:
public static void main(String[] args) throws Exception {
Map<String, Map<String,Integer>> map = new HashMap() {{
put("Color", new HashMap() {{
put("Red", 4);
put("Orange", 1);
put("Blue", 6);
put("Yellow", 2);
}});
}};
System.out.println(getInnerKeyWithLowestValue(map, "Color"));
}
public static String getInnerKeyWithLowestValue(Map<String, Map<String,Integer>> map, String outerKey) {
Map<String, Integer> innerMap = map.get(outerKey);
// Make sure inner map was retrieved
if (innerMap != null) {
Iterator<Map.Entry<String,Integer>> it = innerMap.entrySet().iterator();
Map.Entry<String, Integer> minimum = it.next();
while (it.hasNext()) {
Map.Entry<String, Integer> next = it.next();
if (next.getValue() < minimum.getValue()) {
minimum = next;
}
}
return minimum.getKey();
}
return ""; // Inner map doesn't exist
}
Results:
Orange
If Java 8 is a option for you, it is easy to write a very concise method to do that:
public static String lowestValueKey(Map<String, Map<String, Integer>> map, String key) {
return map.get(key).entrySet().stream()
.min(Comparator.comparing(Map.Entry::getValue))
.get().getKey();
}
Also using Maps inside Maps can be very tedious sometimes. You may consider using Table<String, String, Integer> from Guava library.
Get the Hashmap from the inner hashmap and sort the hashmap based on the value which is shown in the link enter link description here. Obviously firs entry will be the lowest value in your innerhashmap.
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));
}
}
}
I want to create methods which return the amount of same first names and last names, but when i try to test and compile code i get as output 1 , 1 , and this is not true. because there is 10 same names and 10 same last names.
public class Solution
{
public static void main(String[] args)
{
HashMap<String, String> map = createMap();
System.out.println(getCountTheSameFirstName(map, "test"));
System.out.println(getCountTheSameLastName(map, "test"));
}
public static HashMap<String, String> createMap()
{
HashMap<String, String> odin = new HashMap<String, String>();
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
odin.put("test","test");
return odin;
}
public static int getCountTheSameFirstName(HashMap<String, String> map, String name)
{
int count = 0;
for(Map.Entry<String, String> lol : map.entrySet()){
String value = lol.getValue();
if(name.equals(value)){
count++;
}
}
return count;
}
public static int getCountTheSameLastName(HashMap<String, String> map, String familiy)
{
int count=0;
for (Map.Entry<String,String> pair : map.entrySet())
{
String key = pair.getKey();
if (familiy.equals(key))
{
count++;
}
}
return count;
}
}
Please consult the HashMap-API, it is correct by definition: "Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced." (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html#put(K, V))
Sorry!! if you are not use duplicate key then you have to have get the output 10 & 0
Your code: Just I have changed the key and got the output 10 & 0:
public class Solution
{
public static void main(String[] args)
{
HashMap<String, String> map = createMap();
System.out.println(getCountTheSameFirstName(map, "test"));
System.out.println(getCountTheSameLastName(map, "test"));
}
public static HashMap<String, String> createMap()
{
HashMap<String, String> odin = new HashMap<String, String>();
odin.put("0","test");
odin.put("1","test");
odin.put("2","test");
odin.put("3","test");
odin.put("4","test");
odin.put("5","test");
odin.put("6","test");
odin.put("7","test");
odin.put("8","test");
odin.put("9","test");
return odin;
}
public static int getCountTheSameFirstName(HashMap<String, String> map, String name)
{
int count = 0;
for(Map.Entry<String, String> lol : map.entrySet()){
String value = lol.getValue();
if(name.equals(value)){
count++;
}
}
return count;
}
public static int getCountTheSameLastName(HashMap<String, String> map, String familiy)
{
int count=0;
for (Map.Entry<String,String> pair : map.entrySet())
{
String key = pair.getKey();
if (familiy.equals(key))
{
count++;
}
}
return count;
}
}
You are inserting the same key 10 times. The first put works, but each subsequent put replaces the old key/value mapping with the same mapping. The end result is that there's only one key/value pair in the Map, so that's why you get 1 as output.
In short: Your method works as HashMap is designed - you force put to HashMap with same key and first time add value to map, and any other time you just change value of this element because it has same key.
Description:
You have this situation - You are created HashMap like that:
HashMap<String, String> odin = new HashMap<String, String>();
There is first string key and second string value. When you adding value with line:
odin.put("test","test");
You are set value test for key test.
If you repeat that, you will change old element with key test with new element with key test
This results is that entered value is replaced.
Instead of this, you have to put in HashMap something else (array for example) with unique key. In this case you can have 10 inputs with same values.
Here is example of this HashMap:
HashMap<String, String[]> odin = new HashMap<String, String[]>();
In that case you have to provide string key and array of strings which contains values (first names and last names from your question).
I have a method in a class, which initialize a HashMap and put some keys and values inside it, then the method returns the HashMap. How can I retrieve the returned HashMap?
public Map<String, String> getSensorValue(String sensorName) {
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
And here I call this method from another class:
public static HashMap<String, String> sensValues = new HashMap<String, String>();
AllSensors sensVal = new AllSensors();
sensValues.putAll(sensVal.getSensorValue("orientation"));
String something = sensValues.get("x");
But it does not work in this way
sensValues.putAll(sensVal.getSensorValue("orientation"));
Makes my android application crash.
The point is to retrive returned HashMap somehow.
You shouldn't have to copy the map. Just try using the returned reference:
Map<String, String> map = sensVal.getSensorValue("...");
Your method needs to return a Map<String,String>. In the code you have posted, the Map sensorValues is never initialized.
public Map<String, String> getSensorValue(String sensorName) {
Map<String,String> sensorValues = new HashMap<String,String>();
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
Almost as Rich said in his answer, but your method returns a Map which cannot be cast to a HashMap. Try this
Map<String, String> map = sensVal.getSensorValue("...");
Or alternatively change your getSensorValue method so that it returns a HashMap
HashMap sensValues = new HashMap();
Set mapSet = (Set) sensValues.entrySet();
Iterator mapIterator = mapSet.iterator();
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
System.out.println("Key : " + keyValue + "= Value : " + value);
}
Also you can try pass by reference aproach,
void main(){
public static HashMap<String, String> sensValues = new HashMap<String, String>();
AllSensors sensVal = new AllSensors();
sensVal.setSensorValue(sensValues ,"orientation");
String something = sensValues.get("x");
}
public void setSensorValue(Map<String, String> sensorValues, String sensorName) {
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
}