I am trying to get the last KEY from this map in groovy. However, it seems like groovy doesn't have a method for returning the last key in the map.
def person = [fname: "john", sname: "smith", age: 25]
I have tried person.lastKey() and person.lastEntry() but these methods seems to be specific for java only.
You can use person.keySet()[-1] or person.keySet().last()
And to get whole entry use entrySet() instead of keySet()
See the Groovy demo online
lastKey is part of the SortedMap interface and the Groovy map literal gives you an LinkedHashMap, which is the explanation, why your attempts failed.
Maps (the interface SortedMap inherits from) are on their own not ordered or sorted. So what you are asking here, will only work for ordered (which the Groovy map literal will give you) or sorted maps, so make sure you have one of those or you will see random elements instead of what you perceive as last. If order is important consider using a list of key-value-tuples instead.
Related
I am trying to understand what exactly the function "lookup" does in terraform code? does it find maps or lists? just confused how to use this lookup correctly.
The lookup documentation has the following to say about it:
lookup retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.
The normal way to look up a value from a map by key is to use the index syntax, like example["foo"], but that operation will return an error if there is no element with the key foo in the map example.
lookup is therefore similar to the index syntax except for the additional behavior of choosing a fallback value to use instead of an error if the key doesn't exist. lookup(example, "foo", "default") is the same as example["foo"] except that it will produce "default" rather than an error if there is no element with the key "foo".
More recent Terraform versions also have the try function which can serve as a perhaps easier to understand alternative to lookup, because it still uses the normal index syntax as part of the expression: try(example["foo"], "default") is similar to lookup(example, "foo", "default"), and will produce the same result as long as example is a map of strings.
I am trying to add the current dictionary to a Redis list using a dictionary comprehension and then to print out the first (aka current) keys and values of that list. I say current because this is a process I will be continuing with a while loop to have the list building over time, but I have to always access the first keys/values.
I am sure I am totally butchering this, but this is what I have:
adict = {"a":1,"b":2,"c":3}
{rserver.rpush("list",value) for value in adict}
print(float(rserver.lindex("list",0)))
I need to get a list of both keys and values back.
Help would be MUCH appreciated. Thanks!
I am not quite positive on what your redis-list should contain (please include your expected result in the question), but assuming it should at the end of inserts look something like this ["a:1", "b:1", "c:1"], you can achieve this with
adict = {"a":1,"b":2,"c":3}
for key,value in adict.items():
rserver.rpush("list", ":".join([key, value]))
print(float(rserver.lindex("list",0))) #>>> "a:1"
(as you have not included what interface rserver exactly is, it is a bit hard to guess on its exact behavior)
I imagine I'm screwing something up with these declarations, but I've got a groovy class with a field defined like this:
Map<String, SomeType> _someField = [:]
I do inserts like this:
_someField.put( someStringVariable, someTypeInstance )
...and then later, when I check whether a key I know has been mapped is present, the check fails:
_someField.containsKey( someStringVariable )
The only way I can get this to succeed is by calling toString(), like so:
_someField.containsKey( someStringVariable.toString() )
I'm using the generic declaration of the map so my IDE gives me auto completion on the value types, so I'd really like (I think) to keep the type information there.
I've tried changing the key type from String to GString, but to no avail. I've tried changing the map initialization from the groovy shorthand [:] to new LinkedHashMap<>, also to no avail.
Any ideas whether I can keep the type information and avoid having to use toString()?
So this was a case where the variable being fed to containsKey() in the instances where it is failing were of type org.codehaus.groovy.runtime.GStringImpl because they were generated by a function that was performing variable expansion on map values, and that function was creating groovy interpolated strings for values instead of Java Strings.
A quick check on the type of the variable confirmed the type problem, and then it was just a matter of tracking back to find the source of the interpolated string.
Given a Julia object of composite type, how can one determine its fields?
I know one solution if you're working in the REPL: First you figure out the type of the object via a call to typeof, then enter help mode (?), and then look up the type. Is there a more programmatic way to achieve the same thing?
For v0.7+
Use fieldnames(x), where x is a DataType. For example, use fieldnames(Date), instead of fieldnames(today()), or else use fieldnames(typeof(today())).
This returns Vector{Symbol} listing the field names in order.
If a field name is myfield, then to retrieve the values in that field use either getfield(x, :myfield), or the shortcut syntax x.myfield.
Another useful and related function to play around with is dump(x).
Before v0.7
Use fieldnames(x), where x is either an instance of the composite type you are interested in, or else a DataType. That is, fieldnames(today()) and fieldnames(Date) are equally valid and have the same output.
suppose the object is obj,
you can get all the information of its fields with following code snippet:
T = typeof(obj)
for (name, typ) in zip(fieldnames(T), T.types)
println("type of the fieldname $name is $typ")
end
Here, fieldnames(T) returns the vector of field names and T.types returns the corresponding vector of type of the fields.
I have a string like this:
val a = "some random test message"
I have a list like this:
val keys = List("hi","random","test")
Now, I want to check whether the string a contains any values from keys. How can we do this using the in built library functions of Scala ?
( I know the way of splitting a to List and then do a check with keys list and then find the solution. But I'm looking a way of solving it more simply using standard library functions.)
Something like this?
keys.exists(a.contains(_))
Or even more idiomatically
keys.exists(a.contains)
The simple case is to test substring containment (as remarked in rarry's answer), e.g.
keys.exists(a.contains(_))
You didn't say whether you actually want to find whole word matches instead. Since rarry's answer assumed you didn't, here's an alternative that assumes you do.
val a = "some random test message"
val words = a.split(" ")
val keys = Set("hi","random","test") // could be a List (see below)
words.exists(keys contains _)
Bear in mind that the list of keys is only efficient for small lists. With a list, the contains method typically scans the entire list linearly until it finds a match or reaches the end.
For larger numbers of items, a set is not only preferable, but also is a more true representation of the information. Sets are typically optimised via hashcodes etc and therefore need less linear searching - or none at all.