ibaralf
ibaralf

Reputation: 12528

Groovy - Get first elements in multi-dimensional array

I have a groovy list of lists i.e.

list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]

I would like to get a subset of just the first elements of each array

sublist = [2, 1, 1]

I know I can loop through the and just get the first element and add, but I am trying to avoid this since I have a huge array of values. I'm trying to avoid this solution

def sublist = []
list.each {
  sublist.add(it[0])
}

Thanks.

Upvotes: 2

Views: 8756

Answers (3)

Arturo Herrero
Arturo Herrero

Reputation: 13122

A more readable version:

list*.first()

Upvotes: 4

ataylor
ataylor

Reputation: 66069

If you're worried about copying the data, a better approach might be to create a custom iterator, rather than copying the data into another list. This is a great approach if you only need to traverse through the sublist once. Also, if you don't traverse to the end of the sublist, you haven't wasted any effort on the elements you never processed. For example:

bigList =  [[2, 0, 1], [1, 5, 2], [1, 0, 3]]

bigListIter = bigList.iterator()
firstOnlyIter = [
    hasNext: { -> bigListIter.hasNext() },
    next: { -> bigListIter.next().first() }
] as Iterator

for (it in firstOnlyIter) {
    println it
}

You can always turn the iterator back into a list with Iterator.toList().

Upvotes: 1

Rob Hruska
Rob Hruska

Reputation: 120286

You could try:

list.collect { it[0] }

Although that still involves iteration (although somewhat hidden). However, it's likely that any solution is going to involve iteration somewhere down the line, whether it be written by you or the library/API method you call.

Upvotes: 2

Related Questions