How to find same keys and values in HashMap - java

I have an HashMap with names(key) and dates(value) and I need to show if a name that i enter again is a duplicate (I am doing socket programming with different states). Example, I put in the map 3 different names and at the forth time I put a duplicate name.
I tried these codes (they run) but with no success:
HashMap<String, String> map = new HashMap<String, String>();
if(stat.equals("RECEIVE_NAME")){
name = reader.readLine();
if(map.containsKey(name)){
System.out.println("duplicate");
}
}
or
for(Map.Entry<String, String> entry : map.entrySet()){
if(name.equals(entry.getKey())){
sendMessage("duplicate");
}
}
NB: I have a map.put(name) when is not a duplicate after this sequence of blocks. And i know that an hash map can not have duplicate keys :)

A HashMap cannot contain duplicate keys. If you put a key-value pair in a map which already contains the key, the old value will be replaced by the new value.

map.put() returns the previous value associated with key, or null if there was no mapping for key. So you can store that return value and check if is not null:
String check = map.put(name);
if(check != null){
System.out.println("dup: " + check);
}
Use map.putIfAbsent(name) to not overwrite the associated value.

Related

For Each Loop in a Set

I have a HashTable with the following {4:1, 3:56, 4:3, 4:5, 9:89, etc.}
I then make the keys of this Table into a keyset by calling map.keySet().
How can I loop through that set to only output the values associated with the key of 4? I want the output to be 1,3,5, therefore I only want the values associated with the key 4? Is this possible, and if so how.
That's not how maps work. Maps typically only associate one value with each unique key value. So if you have a Map<Integer,Integer> myMap, calling myMap.put(4, newValue), where newValue is some integer, will overwrite the value that was previously mapped to 4. You can have duplicate values though, and you can print all known keys that have been mapped to that value in a map using the following loop.
for (Entry<Integer, Integer> entry : myMap.entrySet()) {
if (entry.getValue().equals(4)) {
System.out.println(entry.getKey());
}
}
A HashMap or a HashTable only maps a key to a value.
Option 1:
If you want to have multiple values for key store it as a list
Map<Integer, List<Integer>> myMap = new HashMap<>();
//To add value for a key
if (!myMap.containsKey(key)) {
myMap.put(new ArrayList<>());
}
myMap.get(key).add(value);
//Get
myMap.get(key); //This will give you the list of value for a given key and null if the key is not present
Option 2:
You can use Google Guava's MultiMap
You can use Google Guava Collections' MultiMap as it allows each key to associate with multiple values.
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put(key, value);
Documentation can be found here: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html

How to add HashMap values to List and print the same

I am trying to add map values to list for my scenario as below.
I have select statement which returns n-no of columns and row, I am storing them into List of Hash Map of type String and pass it to some other method to produce an EXCEL file out of the result.
i am unable to see any data in the list
Please advice where i am going wrong.
while (result.next()) {
resultValues.put("PARTC_ID",result.getString("PARTC_ID"));
resultValues.put("FILE_NME",result.getString("FILE_NME"));
resultValues.put("LOC_ID",result.getString("LOC_ID"));
resultValues.put("CRTE_DTE",result.getString("CRTE_DTE"));
resultValues.put("CRTE_BY",result.getString("CRTE_BY"));
value.add(resultValues); resultValues.clear(); System.out.println(value);
}
You're clearing your Map after adding it to the List. The Map references are all thus the same (and empty)... I think you want to make this change -
// resultValues.clear(); // No, if you need another Map... do this
resultValues = new HashMap<String, String>();
Then to iterate your value List try
for (HashMap<String, String> map : value) {
for (String key : map.keySet()) {
System.out.printf("key[%s] = %s\n", key, map.get(key));
}
}

How to put multiple values in Map from a list

I have a list gotitems.
ArrayList<String> gotitems = new ArrayList<String>();
i need to put that list in a hashmap called map.
Map<String,String> map = new HashMap<String,String>();
i had tried this :
for(String s:gotitems){
map.put("a",s);
}
gotitems contains :
First
Second
Third
But the output of :
System.out.println(map.values());
gives :
Third
Third
Third
i had even tried this :
for(String s:gotitems){
for(int j=0;j<gotitems.size();j++){
map.put("a"+j,s);
}
}
but this is also not working.
What am i doing wrong here ?
As per Map put(K,V) method docs
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
You are ovverriding the key each time here .
for(String s:gotitems){
map.put("a",s);
}
change the key each time and try like
for(String s:gotitems){
map.put(s,s);
}
This is because you are putting all the items in the map against the same key "a"
map.put("a");
You need to store each element against a unique key so add something like this:
int count = 0;
for(String s:gotitems){
map.put("a" + count,s);
count++;
}
You are trying to put three Strings in the map under the same key "a". Try to use unique keys for your values.
You're putting all your items in the Map with the same key: "a".
You should have a unique String key for each value.
For instance:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
Map<String, String> map = new LinkedHashMap<String, String>();
for (String s: list) {
map.put(s, s);
}
System.out.println(map);
Output:
{one=one, two=two, three=three}
Note the LinkedHashMap here: it maintains the order in which you put your key/value pairs.
Edit Of course if your List does not have unique values, moving its values as keys to a Map will overwrite some of the Map's values. In that case you want to ensure your List has unique keys first, or maybe use a Map<Integer, String> with the index of the List's value as key to the Map, and the actual List value as value to the Map.
When you write
for(String s:gotitems){
map.put("a",s);
}
you will trash any existing entry in the map held against the key "a". So after your iteration, your map will contain just one entry corresponding to the last iterated value in gotitems.
To use a map effectively you need to consider what your keys will be. Then use map.put(myKeyForThisItem, s) instead. If you don't have an effective scheme for the keys then using a map is pointless as one tends to use the keys to extract the corresponding values.
As for your second approach, it would be helpful if you could define "it is not working" a little clearer: perhaps iterate through the map and print the keys and values.
Please note that in a map, a key can point to at most one value. In your case, you are doing the following mappings:
"a" -> "one"
then you overwrite it as
"a" -> "two"
then you overwrite it as
"a" -> "three"
remember: a key can point to at most one value. However, a value can be pointed at by multiple keys.
This is wrong:
for(String s:gotitems){
map.put("a",s);
}
Since you are using "a" common key for all values, last inserted key-value pair would be preserved, all previous ones would be overridden.
This is also not correct:
for(String s:gotitems){
for(int j=0;j<gotitems.size();j++){
map.put("a"+j,s);
}
}
you are putting n*n times into map, though you want only n (gotitems.size()) items into map.
First decide on key which you want to use in map, copying List into Map one approach could be use index as key:
for(int j=0;j<gotitems.size();j++){
map.put("KEY-"+j,gotitems.get(j));
}
Output should be:
KEY-0 First
KEY-1 Second
KEY-2 Third
I have reproduce your codes. The problem is that you are assigning the same key to different value. This should work.
import java.util.*;
public class testCollection{
public static void main(String[] args){
ArrayList<String> gotitems = new ArrayList<String>();
gotitems.add("First");
gotitems.add("Second");
gotitems.add("Third");
Map<String,String> map = new HashMap<String,String>();
String x = "a";
int i = 1;
for(String s:gotitems){
map.put(x+i,s);
i++;
}
System.out.println(map);
}
}

Getting the key and its specific value from map

I am using Map as follows
Map<String, String> propMap = new LinkedHashMap<String, String>();
and I saw that there is two methods that I can use keySet() (to get the list of keys)
and values to get the list of values but my question is how to relate between them
for example for key1 the value is 2.
I thought to use get value like follows
Map<String, String> propMap2 = propterm.getPropMap();
Set<String> keySet = propMap2.keySet();
But how I relate it to his respective value ?
You can use propMap.entrySet() method which returns a Map.Entry of key, value, if you want to use every pair of key and value: -
for (Map.Entry<String, String> entry: propMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
Or, if you want to know how to do this with propMap.keySet(), you can iterate over the Set<Key> you obtain, and for each key, use propMap.get(key), to get the value of a particular key: -
Set<String> keySet = propMap2.keySet();
for (String key: keySet) {
System.out.println(propMap.get(key));
}
From an answer from this post: -
With the later approach, if you are regularly accessing the key-value pair, then for each key, the map.get() method is called, which - in the case of a HashMap - requires that the hashCode() and equals() methods of the key object be evaluated in order to find the associated value*. In the first case (entrySet), that extra work is eliminated.

Why result of combining two hashMap is not corecct?

I have two HashMap, first one has 3149 records and the second one 5440 records, when I combine them, the result size is smaller then 3149+5440. Why and how can i solve it?
Map<String,String> bigMap = new HashMap<String, String>();
bigMap.putAll(hashMap1);
bigMap.putAll(hashMap2);
int j = 0;
for (Map.Entry<String, String> entry : bigMap.entrySet()) {
System.out.println(j++);
}
I also cheched with this code to be sure if there is some common key.
for (Map.Entry<String, String> entry : readCsv(hashMap1).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(entry.getKey().equals(hashMap2).get(key))){
System.out.println(i++);
}
}
Your hashMap1 and hashMap probably have a number of same keys. That's why some entries are overridden by other entries with similar keys.
If you have the same keys in the maps, then this is to be expected. Keys must be unique in a map. If you put a value into the map with a key that already exists, then the existing value is overwritten.
To find the common keys you can do
Set<String> common = new HsahSet<String>(hashMap1.keySet());
common.retainAll(hashMap2.keySet());
System.out.println("Common Keys " + common);

Categories

Resources