【问题标题】:How to combine array in groovy?如何在groovy中组合数组?
【发布时间】:2017-09-15 23:50:53
【问题描述】:

以下 java 代码存在,但我正在尝试将其转换为 groovy。我应该简单地将它与 System.arraycopy 保持原样还是 groovy 有更好的方法来组合这样的数组?

  byte[] combineArrays(foo, bar, start) {
    def tmp = new byte[foo.length + bar.length]
    System.arraycopy(foo, 0, tmp, 0, start)
    System.arraycopy(bar, 0, tmp, start, bar.length)
    System.arraycopy(foo, start, tmp, bar.length + start, foo.length - start)
    tmp
  }

谢谢

【问题讨论】:

  • 您不使用列表的任何特殊原因?
  • 如果你要使用数组,我会保持这样......没有必要将数组转换为列表并再次返回只是为了使用一些时髦的风格
  • 嘿@JimmyBond07,你能检查答案并标记最佳答案吗?所以人们知道什么对你有用吗?

标签: groovy


【解决方案1】:
def a = [1, 2, 3]
def b = [4, 5, 6]

assert a.plus(b) == [1, 2, 3, 4, 5, 6]   
assert a + b     == [1, 2, 3, 4, 5, 6]

【讨论】:

  • 所以你可以像 (a?:[]).plus((b?:[])) 或 (a?:[]) + (b? :[])
  • 我会做一个(a+b).findAll()
  • 问题是关于数组,而不是列表。
【解决方案2】:

如果要使用数组:

def abc = [1,2,3,4] as Integer[] //Array
def abcList = abc as List
def xyz = [5,6,7,8] as Integer[] //Array
def xyzList = xyz as List

def combined = (abcList << xyzList).flatten()

使用列表:

def abc = [1,2,3,4]
def xyz = [5,6,7,8]
def combined = (abc << xyz).flatten()

【讨论】:

  • 这会破坏 abc。如果您需要带有原始内容的 abc,则此解决方案将不起作用。
【解决方案3】:
def a = [1, 2, 3]
def b = [4, 5, 6]
a.addAll(b)
println a

&gt;&gt; [1, 2, 3, 4, 5, 6]

【讨论】:

    【解决方案4】:

    诀窍是 flatten() 方法,它将嵌套数组合并为一个:

    def a = [1, 2, 3]
    def b = [4, 5, 6]
    def combined = [a, b].flatten()
    
    assert combined == [1, 2, 3, 4, 5, 6]
    
    println(combined)
    

    要删除空值,您可以像这样使用 findAll():

    def a = null
    def b = [4, 5, 6]
    def combined = [a, b].flatten().findAll{it}
    
    assert combined == [4, 5, 6]
    
    println(combined)
    

    【讨论】:

      【解决方案5】:

      我会去的

      byte[] combineArrays(foo, bar, int start) {
        [*foo[0..<start], *bar, *foo[start..<foo.size()]]
      }
      

      【讨论】:

      • 确实非常棒。我喜欢!
      • 你不能用foo[start..&lt;foo.size()]代替foo[start..-1]
      • 如果您使用列表,您可以。对于阵列,您将不得不等到 GROOVY-4665 得到修复
      【解决方案6】:

      可以这样做:

      def newCombine(foo,bar,start) {
         ([].add + foo[0..<start]+bar+foo[start..<foo.size()]).flatten()
      }
      

      它适用于各种数组(byte[])或列表

      【讨论】:

      • 我会将您的代码更改为 def newCombine(foo,bar,start) { def res = [] res
      【解决方案7】:

      如果数组未定义,上述所有解决方案都会失败:

      def a = [1,2]
      def b
      assert a+b == [1, 2, null]
      

      这可能不是你想要的。

      添加前要么测试数组是否存在:

      def a = [1,2,3,4]
      def b // null array
      def c = [0,4,null,6]
      def abc = []
      [a,b,c].each{ if (it) abc += it }
      assert abc == [1, 2, 3, 4, 0, 4, null, 6] 
      

      ,或者全部相加,然后过滤输出:

      (a+b+c).findAll{ it != null }
      

      (这里假设 null 在原始数组中不是有效值,这意味着第一个解决方案要好得多,即使它看起来不够 Groovy。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 2019-06-21
        • 2016-07-17
        相关资源
        最近更新 更多