Skip to content

Instantly share code, notes, and snippets.

@marcusvoltolim
Created April 26, 2022 18:03
Show Gist options
  • Save marcusvoltolim/a7390ced31ec5203a79e173991b5f57f to your computer and use it in GitHub Desktop.
Save marcusvoltolim/a7390ced31ec5203a79e173991b5f57f to your computer and use it in GitHub Desktop.
//##### 1. Adicionando elemento ao final da lista com método leftShift ou operador <<
List<Integer> lista1 = [1].leftShift(2).leftShift(3).leftShift(4) // Lista resultante [1, 2, 3, 4]
List<Integer> lista2 = [1] << 2 << 3 << 4 // Lista resultante [1, 2, 3, 4]
List<Integer> lista3 = [] << 1 << 2 << 3 << 4 // Lista resultante [1, 2, 3, 4]
List<Integer> lista4 = []
lista4 << 1 << 2 << 3 << 4 // Lista resultante [1, 2, 3, 4]
//##### 2. Concatenando listas com método plus ou operador +
List<Integer> listaPlus1 = [1, 2, 3].plus([4, 5, 6]).plus([7, 8]) // Lista resultante [1, 2, 3, 4, 5, 6, 7, 8]
List<Integer> listaPlus2 = [1, 2, 3] + [4, 5, 6] + [7, 8] // Lista resultante [1, 2, 3, 4, 5, 6, 7, 8]
//##### 3. (Groovy) Adicionando vários elementos à partir de uma posição com método plus
List<Integer> listaPlus3 = [1, 2, 3].plus(0, [4, 5, 6]) // Lista resultante [4, 5, 6, 1, 2, 3]
//#### Extra. Intercalando plus e leftShift
List<Integer> listaExtra = ([1, 2, 3] << 4) + [5, 6] + [7, 8] << 9 << 10 //Lista resultante: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Como + tem precedência sobre <<, é necessário os parenteses, pois existe + (plus) para outros tipos: Integer, String...
// Ambos métodos Groovy retornam a lista modificada, ou seja, com os elemento(s) inserido(s).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment