HashMap model1 = wordobject.getMap();
Set sample = model1.keySet();
Iterator it = sample.iterator();
==
Can you please explain me the above 3 lines?
I see that we are trying to get the hash table from the object and get it assigned to the HashMapmodel1.
1) what is keyset?
2) what does .iterator do?
You are declaring a typical Java HashMap in the first line (a little obvious). You usually construct a HashMap using generics for key value pairs: HashMap<K,V>
The Java API HashMap class allows you to get a set of the keys used for the HashMap. The keySet() method returns a Set<K>.
An iterator allows you to iterate through the set calling methods like next() and hasNext(). It is a way to traverse the set sequentially.
A Hashtable != HashMap
The documentation for Map#keyset() says Returns a Set view of the keys contained in this map
The documentation for Iterator in Java - a more general discussion can be found on Wikipedia
the ketSet() is clearly going to return a Set object (hence when we are instantiating the Set object, sample, with it's result). This Set contains all of the Key Values from the HashMap. Its type will be whatever type the Keys in the hasMap were. The iterator provides a way to step through the elements of the set.
oh and as someone pointed out, we are getting a HashMap from wordobject.
An iterator allows you to loop through the Set. A Set is like an ArrayList but does not allow you to index it. Quick google of set or iterator will give you some more info about them both. Here's a link that explains iterators: http://www.java-samples.com/showtutorial.php?tutorialid=235
1) keySet() is a method on map that returns all the keys for the map. Just to make it clearer, map is like a collection of pairs. i.e. each item in a map has a key and a value associated with it. Like a english dictionary, where each item in the dictionary is a word (the key) and a corresponding meaning (the value). So, keySet() will return a set of all the keys, i.e. the words in the dictionary.
2).iterator() returns an Iterator for the set. You can use the iterator "it" to iterate through the items in the set by using its methods like "next()", "hasNext()", "remove()".. etc..
Read up a little more Java docs to learn more.
Related
I have a Map<String, List<List<Double>>> with only one key, e.g.
{onlyKey=[[1.0, 2.3, 20.1], [6.5, -9.3, 4.5]]}
But I don't actually know what the name of the key is.
How can I get the name of the only key stored within the map?
Answered here.
I know that keySet exists, but I already tried map.keySet().get(0) and Set doesn't have a get(int) method. Pretty sure sets are generally used when you know (or have some idea of) what they contain.
The Map<First, Second> has the method keySet() that returns a Set<First> of the key.
Also: There's entrySet() that returns a Set<Entry<First, Second>>.
Note that return is a Set and not a List, the order of insertion is not preserved nor you have access to get(int index), you need to iterate over a set to get a first value.
From the Map Documentation you can see you can use keySet() to recover the Set of all keys in your Map, which, in your case, will contain your only key.
As an alternative for using iterator you might use stream() and findFirst():
map.keySet().stream().findFirst().get()
I used map.keySet().iterator().next() to get the only key within the map.
I'd would like to use a collection of "key - value" pairs:
Which is the base for a JTable data model (TableModel implementation), so I need to access elements by their index/position (e.g. to implement Object getValueAt(int rowIndex, int columnIndex)). The collection must preserve the order of the elements. An ArrayList would be good for that.
Which allows to retrieve elements by the value of the key. A HashMap would be good for that.
The closest usable collection I've found is LinkedHashMap. It preserves the order and allows retrieval by key. However the access to an item is not possible by index/position, I must iterate over the items until the good one is found. This is not be time-effective.
Is there a better one than this one?
Thanks.
(Question is similar to this one, but the solution provided uses the conversion toArray() which is not time-effective. If the set of pairs changes, the conversion needs to be done again.)
There is no such collection implementation in the JRE.
But you can easily overcome this issue by using a Map<K,V> for storing the key-value pairs and an additional List<K> to store the keys in sequential order. You can then access a value either by key or by index using: keyValueMap.get(keys.get(index)).
You must make sure that modifications are always synchronized on both collections:
Add/Change an entry: if (keyValueMap.put(key, value) == null) keys.add(key)
Remove an entry: if (keyValueMap.remove(key) != null) keys.remove(key)
Note that this implementation assumes that values are never null. In case null values are required too, the code gets slightly more complex as we have to check for existence of an entry using keyValueMap.contains(key).
Without implementing your own collection, it might be easiest to just have two collections, with the key-value reversed in the second one but otherwise ordered the same.
(wanted this to be a comment, but not enough rep yet)
Apache Commons Collection has a ListOrderedMap class that makes what you want.
I'm looking at a java hangman game here: https://github.com/leleah/EvilHangman/blob/master/EvilHangman.java
The code in particular is this:
Iterator<Entry<List<Integer>, Set<String>>> k = partitions.entrySet().iterator();
while (k.hasNext())
{
Entry<?, ?> pair = (Entry<?, ?>)k.next();
int sizeOfSet = ((Set<String>)pair.getValue()).size();
if (sizeOfSet > biggestPartitionSize)
{
biggestPartitionSize = sizeOfSet;
}
}
Now my question. My google foo is weak I guess, I cannot find much on Entry sets other than the java doc itself. Is is just a temporary copy of the map? And I cannot find any info at all on the syntax:
Entry<?, ?>
Can anyone explain or point me toward an explanation of what is going on with those question marks? Thanks in advance!
An entrySet is the set of all Entries in a Map - i.e. the set of all key,value pairs in the Map. Because a Map consists of key,value pairs, if you want to iterate over it you need to specify whether you want to iterate over the keys, the values, or both (Entries).
The <?,?> indicates that the pair variable holds an Entry where the key and the value could be of any type. This would normally indicate that we don't care what types of values it holds. In your code this is not the case, because you need to cast the value to Set<String> so you can check its size.
You could also rewrite the code as follows, avoiding the cast to Set<String>
Iterator<Entry<List<Integer>, Set<String>>> k = partitions.entrySet().iterator();
while (k.hasNext())
{
Entry<?, Set<String>> pair = (Entry<?, Set<String>>)k.next();
int sizeOfSet = pair.getValue().size();
if (sizeOfSet > biggestPartitionSize)
{
biggestPartitionSize = sizeOfSet;
}
When we need to be more specific about the types that the Entry holds, we can use the full type: Entry<List<Integer>, Set<String>>. This avoids the need to cast the key or value to a particular type (and the risk of casting to the wrong type).
You can also specify just the type of the key, or the value, as shown in my example above.
You can find information about Entry in the Javadoc:
http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
The <?, ?> part is because Entry is a generic interface.
More info on ? here: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
That being said, the usage in this example is not very nice. A cleaner way of getting sizeOfSet:
int sizeOfSet = k.next().getValue().size();
You aren't supposed to know much about the entrySet() function returns. All you are allowed to depend on is that it is a Set<Map.Entry<x,y>>. It might be a rather special (*) copy, but it's more likely to be an object that provides a view of the innards of the original Map.
In modern Java, this sort of thing get commonly written as:
for (Map.Entry<X, Y> me : map.entrySet()) {
// code that looks at me.xxx() here
}
In your example, X,Y is List<Integer>, Set<String>.
(*) The documentation says, 'The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.'
Thanks to #Miserable Variable.
Entry<?, ?>
Can anyone explain or point me toward an explanation of what is going on with those question marks?
I could be wrong but I think the programmer is trying to be lazy. It should have been
Entry<List<Integer>, Set<String>>>
then none of the casts would have been required
ALSO:
My google foo is weak I guess, I cannot find much on Entry sets other than the java doc itself. Is is just a temporary copy of the map?
Javadoc has everything you need (emphasis mine):
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined.
The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations.
It does not support the add or addAll operations.
What more information are you looking for?
I'm looking for a method like:
myMap.containsKeyStartingWith("abc"); // returns true if there's a key starting with "abc" e.g. "abcd"
or
MapUtils.containsKeyStartingWith(myMap, "abc"); // same
I wondered if anyone knew of a simple way to do this
Thanks
This can be done with a standard SortedMap:
Map<String,V> tailMap = myMap.tailMap(prefix);
boolean result = (!tailMap.isEmpty() && tailMap.firstKey().startsWith(prefix));
Unsorted maps (e.g. HashMap) don't intrinsically support prefix lookups, so for those you'll have to iterate over all keys.
From the map, you can get a Set of Keys, and in case they are String, you can iterate over the elements of the Set and check for startsWith("abc")
To build on Adel Boutros answer/comment about the efficiency of iterating keys, you could encapsulate key iteration in a Map subclass or decorator.
Extending HashMap would give you a class to put the method in and keep map-specific code out of your method, so lowering complexity and making the code more natural to read.
Why doesn't Java provide functions to get the key/value pairs in a HashSet like exists in Hashtable? It seems like a real pain to have to iterate over it every time you need to get at something. Or is there an easier way to do this?
HashSet doesn't have key/value pairs. It is a Set of objects and you would use an implementer of Set to ensure that a collection of objects contained no duplicates.
Implementers of Map like HashMap have key/value pairs and provide a get(Object key) method to get the value associated with a key.
Since a Set doesn't contain keys and values, there is no way such a view could be provided.
What would you consider to be the key and what would be the value in a Set?
A Set don't have any key/value pairs, just (unique) values. As you already said you get these values via the Iterator or by returning an array with these values with the toArray() method.
Maybe you are looking for a List instead.