Reputation: 13811
I have been learning Groovy for a week, but I have a problem: I need to store the combinations of words to the corresponding ascii values. For example the combinations of the word "the" and the sum of the ascii values of each characters is 10(not exactly,but still for example).
There are, obviously, other words where the sum of ascii values is 10. I want a data structure where I can look up the value 10 and get the words where the sum of the ascii values is 10. I can't do this in Groovy Map, because the key value should be unique. How to do this in Groovy?
Upvotes: 0
Views: 137
Reputation: 171184
You could do something like this as well:
def words = [ 'the', 'het', 'love', 'groovy' ]
words.groupBy { ( it as char[] ).collect { it as int }.sum() }
That gives you the map:
[321:[the, het], 438:[love], 678:[groovy]]
Upvotes: 3
Reputation: 8078
Here's a small example that initiates a Map
that returns an empty List
in case a key is requested for the first time using the withDefault
method:
def map = [:].withDefault { [] }
map[10] << 'the'
map[10] << 'as'
map[20] << 'from'
assert map[10] == ['the', 'as']
assert map[20] == ['from']
Upvotes: 2
Reputation: 340973
You need a multi-map data structure. One can be found in Apache Commons, another one in Guava.
In Groovy you can use a simple Map
of int
-> list
, with default value for convenience.
Upvotes: 1
Reputation: 96957
A map of Int to List of String should fix this. Simply append the words having the same sum, to the list corresponding to a key.
Upvotes: 1