开发者

Which implementation need to be selected in Groovy, for this problem?

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 word开发者_高级运维s 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?


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]]


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']


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜