How could i make HashSet as parameter to the HashMap? - java

I have to maintain the list of indexes for each of the key value in HashMap.
So i declared HashMap as
HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()> hm = new HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()>();
but the above declaration seems to be not correct.
So i declared it as
HashSet<Integer> hset = new HashSet<Integer>();
but here the problem is,how could i declare the type of objects stored in HashSet i,e Integer, bacause in the above declaration the HashSet is rawtype.

I would like to add more here,
You need to initialize your outer Map like below
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer,HashSet<Integer>>();
and inner collection like this
HashSet<Integer> hset = new HashSet<Integer>();
And you insert the values like below in map and your hash set.
hset.add(1);
hset.add(2);
map.put(100,hset);
hset = new HashSet<Integer>();
hset.add(3);
hset.add(4);
map.put(101,hset);
So every time you need new instance of HashSet to put in map.
You can get inner HashSet by using Map key you used to insert.
HashSet<Integer> hset=map.get(100); //Same map

Here is your declaration should look like
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer>,HashSet<Integer>>
Second declaration you have provided for Hashset is correct. Its not raw type. Did you try adding a any other type of element to it ?

Try this it will work :
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
you can easily Set Using Map tag only .
or
Create the Object Of Hashmap and put the value from Refrence. it will work

Related

How to initialize a HashMap with TreeSets as values?

I am trying to create a HashMap using strings as keys and tree sets sorted using a custom comparator (CandidateComparator) as values.
HashMap<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>(new CandidateComparator())>();
I can't see what I've done wrong. I was using this site:
http://www.java2novice.com/java-collections-and-util/treeset/sort-by-objects/
as a reference.
This statement yields two syntax errors:
1. Insert '>' to complete ReferenceType1;
2. Expression expected after this token '(' - refers to the last '(' of the statement.
What am I doing wrong?
The Comparator refers to the TreeSet, not the HashMap. Moreover, the Comparator is not part of the TreeSet's type definition (as is, for example TreeSet<Candidate>) - it's only passed when a new instance is created.
So, to make a long story short - drop it from the definition and pass it when you construct an object:
Map<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>>();
map.put ("SomeString", new TreeSet<Candidate>(new CandidateComparator()));
The HashMap should be initialized this way:
HashMap<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>>();
No Comparator is required for the HashMap itself. You'll need instances of TreeSet to populate the HashMap, and each of them would require a Comparator.
Comparator<Candidate> cmp = new CandidateComparator();
TreeSet<Candidate> ts1 = new TreeSet<Candidate>(cmp);
... populate ts1 ...
map.put ("someKey1", ts1);
TreeSet<Candidate> ts2 = new TreeSet<Candidate>(cmp);
... populate ts2 ...
map.put ("someKey2", ts2);

iterate through all the values of a key in hashtable java

Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");
How can I iterate through all values of "a single key"?
key:1
values: student1, student2
You need to use:
Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();
and add the new String value for a particular key in the associated List.
Having said that, you should use a HashMap instead of Hashtable. The later one is legacy class, which has been replaced long back by the former.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
then before inserting a new entry, check whether the key already exists, using Map#containsKey() method. If the key is already there, fetch the corresponding list, and then add new value to it. Else, put a new key-value pair.
if (map.containsKey(2)) {
map.get(2).add("newValue");
} else {
map.put(2, new ArrayList<String>(Arrays.asList("newValue"));
}
Another option is to use Guava's Multimap, if you can use 3rd party library.
Multimap<Integer, String> myMultimap = ArrayListMultimap.create();
myMultimap.put(1,"student1");
myMultimap.put(1,"student2");
Collection<String> values = myMultimap.get(1);
A Hashtable doesn't store multiple values for a single key.
When you write ht.put(1, "student2"), it overwrites the value that goes with "1" and it is no longer available.
Hashtable doesn't allow multiple values for a key. When you add a second value to a key, you're replacing the original value.
If you want multiple values for a single key, consider using a HashTable of ArrayLists.

How to create and push dynamic elements in HashMap

static Map<Integer,HashMap<String,HashMap<String,String>>> maps = new HashMap<Integer, HashMap<String,HashMap<String,String>>>();
I want to insert the elements inside the HashMap I declared above , the inner most hashmap has values ready which I can use , now I am using it like ,
static Map<String,String> values = new HashMap<String, String>();
maps.put(1, new HashMap<<new String("")>, values>());
How can I achieve this ?
static Map<String,String> values1 = new HashMap<String,String>();
static Map<String,Map<String,String>> values2 = new HashMap<String,Map<String,String>>();
values2.put("", values1);
maps.put(1,values2);
btw, if you have java 7, you can use:
Map<String,String> values1 = new HashMap<>();
and so on for others
In cases you have map inside a map (inside a map), consider using Apache MultiKeyMap.
Coding will be more intuitive
It will improve the readability of your code
It will prevent many if(map.get(key) != null) blocks you will probably have in your code.
Why not to have instance of HashMap. When you wan to insert new value, you need to have Integer, String, String key and String value.
You continuously select nested HashMaps according to keys and then insert value to the most inner HashMap.
map.get(key1).get(key2).insert(key3, value)

unmodifiable collection issue when retainall is used for two key sets in java

Map<String,String> map=request.getParameterMap();
^ is the unmodifiable map.
Set s1= map.keySet();
Set s2= map2.keySet();/* another keyset of local map*/
Using s1.retainAll(s2) throws an exception: at java.util.collections$unmodifiablecollection.retainall
Here request.getParameterMap() returns an unmodifiable map.. I tried creating a local map. But the issue stil persists.
Suggest some solution.
The Set.retainAll method modifies the set it's being called on. Assuming the keySet method of you unmodifiable map is just a view on to the underlying map, it shouldn't allow modifications. You probably want to create a new (modifiable) set and then remove items from it:
Set s1 = new HashSet(map.keySet());
s1.retainAll(s3);
You are not allowed to modify the keyset of an unmodifiable map as the keyset returned is also unmodifiableSet. You can create a local map from the unmodifiableMap and than use retainAll on local map keyset.
Map map1 = new HashMap();
map1 = Collections.unmodifiableMap(map1);
Map map2 = new HashMap();
Map map3 = new HashMap(map1);
Set s1 = map1.keySet();
Set s2 = map2.keySet();
Set s3 = map3.keySet();
s3.retainAll(s2);

Java: can I have arrays in Hashmaps?

Can I have arrays in Hashmaps ?
If so, what's the exact syntax to declare such hashmap ?
thanks
Arrays are objects, too. Even primitive arrays like int[].
Map<String,String[]> map = new HashMap<String,String[]>();
Value? that's fine, an array is an Object.
Key? Not so easy - see here:
Using a byte array as Map key
Yes. Below is an example that uses int [] as values. Example here.
Map<String, int[]> map = new TreeMap<String, int[]>();
HashMap<String, String[]> ab = new HashMap<String, String[]>();
I think you should use ArrayList instead of a primitive array. Becouse of the == comparision done inside of the HashMap class.
So, you could have something like this:
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
When the map checks if some element (given its key "k") is present in the array it computes its hashcode. If there's some element at that position "k", then a colision may be produced, so it checks if the elements are the same. Something that can have some troubles with primitives arrays.

Categories

Resources