2017年1月28日 星期六

[ GroovyGN ] Take Or Drop Last Items From a Collection

Source From Here
Preface
We know Groovy has a lot of nice methods for working with collections. For example in previous blog posts we have seen how to take or drop elements from a list and even with a conditionSince Groovy 2.4 we can now also use the dropRight and takeRight methods to take or drop elements from the end of the list.

Example
In the following example we have a simple list and we use the dropRight and takeRight methods to get elements from the list:
> list = ['Simple', 'list', 'with', 5, 'items']
===> [Simple, list, with, 5, items]
> list.takeRight(1)
===> [items]
> list.takeRight(2)
===> [5, items]
> list.takeRight(0)
===> []
> list.takeRight(6) // Out of boundary is handling
===> [Simple, list, with, 5, items]
> list.dropRight(1) // New List is returned
===> [Simple, list, with, 5]
> list.dropRight(3)
===> [Simple, list]
> list.dropRight(5)
===> []
> list.dropRight(0)
===> [Simple, list, with, 5, items]
> list // drop operation won't impact original list
===> [Simple, list, with, 5, items]
> array = ['Rock on!', 'Groovy baby!'] as String[]
===> [Rock on!, Groovy baby!]
> array.class.name
===> [Ljava.lang.String;
> array.takeRight(1)
===> [Groovy baby!]
> array.dropRight(1)
===> [Rock on!]
> range = 0..10
===> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> range.takeRight(2)
===> [9, 10]
> range.takeRight(4)
===> [7, 8, 9, 10]
> range.dropRight(5)
===> [0, 1, 2, 3, 4, 5]



沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...