What is Groovy's alternative for Java 8's .map()
?
Example:
List<String> codes = events
.stream()
.map(event -> event.getCode())
.collect(Collectors.toList());
I was trying to do
events.each { it; return it.getCode() }.collect() as String[]
but I am getting List
of String
s, but toString()
representation instead of code
Groovy 2.5. 0 and above adds toList and toSet methods as enhancements to Stream. No need to use Collectors.
We can iterate through entries using the each() and eachWithIndex() methods. The each() method provides implicit parameters, like entry, key, and value, which correspond to the current Entry. The eachWithIndex() method also provides an index in addition to Entry. Both the methods accept a Closure as an argument.
Stream is an interface and T is the type of stream elements. mapper is a stateless function which is applied to each element and the function returns the new stream. Example 1 : Stream map() function with operation of number * 3 on each element of stream.
Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.
Consider the collect
method as illustrated below:
class Event {
def code
def name
}
def events = []
events << new Event(code: '001', name: 'a')
events << new Event(code: '002', name: 'b')
def codes = events.collect { it.code }
assert ['001','002'] == codes
Note that an equivalent Groovy idiom is the spread-dot operator:
def codes = events*.code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With