开发者

How to select values 2+ after any number in a list?

开发者 https://www.devze.com 2023-04-04 02:20 出处:网络
Is there any way to select the seco开发者_JAVA百科nd, third (etc) value from a value in a list in Groovy? I\'m still very new to programming in general and am just wondering if there is an easy way to

Is there any way to select the seco开发者_JAVA百科nd, third (etc) value from a value in a list in Groovy? I'm still very new to programming in general and am just wondering if there is an easy way to do this.

For example, if I have the list

[1, 2, 3, 4, 5, 6]

I want to select the next two values after each value using a for loop:

for 1: (1, 2, 3)
for 2: (2, 3, 4)

...and so on.

Is that easily possible? Thanks in advance!


If you're using groovy 1.8.1 or later, you can use the take and drop methods:

def foo = [1, 2, 3, 4, 5, 6]
foo.size().times { i ->
    println foo.drop(i).take(3)
}

This will result in

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]

If you want the iteration to stop at the last group of three, try something like this:

def foo = [1, 2, 3, 4, 5, 6]
if (foo.size() > 2) {
    (foo.size() - 2).times { i ->
        println foo.drop(i).take(3)
    }    
}

which gives

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]


If you're not using Groovy 1.8.1+, then you can acheive a similar result by writing a function like so:

List split( List foo, int size ) {
  (0..foo.size()-size).collect { foo[ it..it+size-1 ] }
}

Then, you can call this like:

split( [1, 2, 3, 4, 5, 6], 3 )

to print

[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
0

精彩评论

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

关注公众号