How to select all values from an array or list?
I'm super new to programming and I'm wondering how to tackle one of the most basic problems out there-- the "FizzBuzz" thing. I'm doing this in Groovy.
I have a pretty specific idea of how I want the code to be constructed, but I can't for the life of me figure out how to test something against each value in an array.
What I mean is, say, for each value in list [1,2,3,4], how would I go about checking if each value is even? I know I can select each specific point in the array but that's not what I want-- I'd like to be abl开发者_JAVA技巧e to say something like "if n%2=0, label this even."
That's a very basic example, but you probably get the idea. Any help would be greatly appreciated.
Groovy allows you to tackle this problem with a functional approach. By applying a mapping transformation, you can generate a list of pairs containing the number and whether it's even or odd.
All groovy lists have a method called collect
for mapping a closure over each element. The return value is a list containing the result the closure being called on each element. For example:
[1, 2, 3, 4].collect {
[it, it % 2 ? 'odd' : 'even']
}
===> [[1:odd], [2:even], [3:odd], [4:even]]
This results in a list of pairs (actually 2 element lists). It's pretty common to want the result to be a map instead of a list, and groovy has a specialized version of collect
, called collectEntries
just for this. Here's an alternative that returns a map:
[1, 2, 3, 4].collectEntries {
[it, it % 2 ? 'odd' : 'even']
}
===> {1=odd, 2=even, 3=odd, 4=even}
I would do something like:
def list = [1, 2, 3, 4]
def map = [:]
list.each {
if (it % 2 == 0)
map.putAt(it, "even")
else
map.putAt(it, "odd")
}
println map
this would print: [1:odd, 2:even, 3:odd, 4:even], you can do whatever you want within the 'if else' statements, but i think what you're asking is how to iterate through a collection one member at a time, the 'each' closure is the primary way to do this.
精彩评论