I am currently trying to split a string 1128-2 so that I can have two separate values. For example, value1: 1128 and value2: 2, so that I can then use each value separately. I have tried split() but with no success. Is there a specific way Grails handles this, or a better way of doing it?
Try:
def (value1, value2) = '1128-2'.tokenize( '-' )
How are you calling split? It works like this:
def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'
def (value1, value2) = '1128-2'.split('-') should work.
Can anyone please try this in Groovy Console?
def (v, z) = '1128-2'.split('-')
assert v == '1128'
assert z == '2'
You can also do:
Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer
//a=1182 b=2
split doesn't work that way in groovy. you have to use tokenize...
See the docs:
http://groovy-lang.org/gdk.html#split()
dependencies {
compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
def (g, m) = i.tokenize( ':' )
dep.exclude group: g , module: m
}
}
}
Related
The following method is supposed to count the number of occurrences of every char in a given string:
def countLetters(text: String): Map[Char, Int] = ???
For example, the input string "aabaabcab" should be mapped to
Map(a -> 5, b -> 3, c -> 1)
Here is a straightforward iterative approach:
def countLetters(text: String): Map[Char, Int] = {
val h = collection.mutable.HashMap.empty[Char, Int]
for (c <- text)
h(c) = h.getOrElse(c, 0) + 1
h.toMap
}
Is there any way to implement it without looping and explicitly allocating mutable hash maps?
Today finally did it! This is what worked for me:
text.foldLeft(Map[Char, Int]() withDefaultValue 0){(h, c) => h.updated(c, h(c)+1)}
Good luck on your next ones if you are reading this! ;)
def anti_vowel(t):
v = "aeiouAEIOU"
g = ""
for i in t:
for c in v:
if i == c:
g = g + i
print(g)
anti_vowel("umbrella")
o/p : uea
Why am I getting the o/p with only vowels but i wanted to do the exact opposite?
To make your code work, you can either switch to using in, or use a for-else statement and break if you do have a vowel match:
def anti_vowel(t):
v = "aeiouAEIOU"
g = ""
for i in t:
for c in v:
if i == c:
break
else:
g += i
return g
which does now give the intended output! :)
If you were after something slightly more efficient, you could use a generator with str.join:
def anti_vowel(t):
v = "aeiouAEIOU"
return ''.join(c for c in t if c not in v)
which we can see works:
>>> anti_vowel("umbrella")
'mbrll'
Note that using in is faster than a for-loop as the operation is much more optimised at the low-level. It also produces much more readable (or Pythonic) code.
Oh and btw I believe functions should always have an output - even if the intention is to print that output, so I have used returns instead.
Try this.
def anti_vowel(t):
v = "aeiouAEIOU"
r=[t]
[r.append(r[-1].replace(l,'')) for l in v]
return r[-1]
I am trying to understand if the following Groovy syntax is correct:
String f() { return "Hello"}
String g() { return "World"}
Map myMap = [
a : f(),
b : g(),
]
String x = myMap['a']
String y = myMap['b']
assert x == "Hello"
assert y == "World"
The Groovy language reference documentation on maps is not clear in this regard:
http://docs.groovy-lang.org/latest/html/documentation/index.html#_maps
Yes it's correct. Your case is covered in the first example in the documentation.
def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']
Think of the syntax as something like this: [value: expression]
The keys a and b become strings (value) and the methods are called to evaluate the expressions.
I want to check who can come up with the best Groovy-sh way to achieve this -
def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]]
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]]
I want result
[["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]]
I'm currently iterating the maps and doing this. I'm looking for a solution using Gpath and findAll
Thanks,
Sreehari.
You can transpose both lists and get the entry (id or t) from each list:
def fn = { m1, m2 ->
return [m1,m2]
.transpose()
.collect { [ id: it.first().id, t: it.last().t ] }
}
def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]]
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]]
assert fn(m1, m2) ==
[["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]]
You can use transpose to zip the maps into pairs, then combine the pairs and filter by map key:
[m1, m2]
.transpose()
.collect { (it[0] + it[1]).subMap(['id', 't']) }
which evaluates to
[[id:1, t:t1], [id:1, t:t2], [id:2, t:t1]]
This works in groovysh using groovy-2.4.4, with either jdk7 or jdk8.
Hi I have a map like this :
[this:0, is:1, a:2, file:3, anotherkey:4, aa:5]
I wish I could find the key's given the value of a map. For example, if the value 5 is given I need to return aa from the map.
Is that possible?
I don't know if there's a direct method to get a key for a given value, but using Map#find to get a map entry and then get its value should be enough:
def keyForValue(map, value) {
map.find { it.value == value }?.key
}
def map = [a: 1, b: 2, c: 3]
assert keyForValue(map, 2) == 'b'
assert keyForValue(map, 42) == null
In general, maps don't need to have an order relation between their entries, but the default implementation for Groovy's literal maps is LinkedHashMap, which is ordered, so the keyForValue will always yield the first key for a value when using those maps.
There's no specific command for that.
Fortunately, as showed here, you can easily get the key(s) for a specific value in a map:
def myMap = [this:0, is:1, a:2, file:3, fix:4, aa:5]
def myValue = 5
You can do:
def myKey = myMap.find{ it.value == myValue }?.key
// 'aa'
If you want all the keys, do something like this:
def myMap = [this:0, is:1, a:2, file:3, fix:4, aa:5, bb:5]
def myValue = 5
def myKeys = []
myMap.findAll{ it.value == myValue }.each{myKeys << it?.key}
// ['aa', 'bb']
You could invert the map, like this:
Map m = [a: '1', b: '2']
Map mInvert = m.collectEntries { e -> [(e.value): e.key] }
assert mInvert == ['1':'a', '2':'b']
assert mInvert['2'] == 'b'
assert m['b'] == '2'
You'll probably have to iterate over the entry set yourself and try to find the entry with a matching value.
def expect = 5
def m = ['this':0, is:1, a:2, file:3, aa:5]
def r = m.collectMany{ k,v -> (v == expect) ? [k] : []}
// Result: [aa]