This example will show how to transform a list to a map using groovy. In the set up we will create a Bike class while initializing a list of bikes which will be used in the first snippet. In a comparable example we demonstrate how to convert an arraylist to a map in java using java 8 and guava.
Setup
@ToString
class Bike {
def name
def brand
public Bike(String name, String brand) {
this.name = name
this.brand = brand
}
}
def bikes
@Before
void before() {
bikes = [
new Bike("SuperFly", "Trek"),
new Bike("X-Caliber", "Trek"),
new Bike("Big Daddy", "Huffy"),
new Bike("CranBrook", "Huffy"),
]
}
Convert list of objects to map
Using collectEntries
we will iterate over the collection of bikes and transform each bike object in the list to a map entry using the bike name as the key and the brand as the value.
@Test
void convert_list_of_objects_to_map() {
def bikeMap = bikes.collectEntries {
b -> [b.name, b.brand]
}
assert 4 == bikeMap.size()
assert 'Trek' == bikeMap['SuperFly']
}
Output
[SuperFly:Trek, X-Caliber:Trek, Big Daddy:Huffy, CranBrook:Huffy]
List of strings to map
Using a SpreadMap we will convert a list of strings into a map. A SpreadMap is a helper that turns a list with an even number of elements into a Map. In the snippet below, we create a map keyed by NFL city while the value will be the team name.
@Test
void convert_list_of_strings_to_map() {
def list = [
'green bay',
'packers',
'cincinnati',
'bengals'] as Object[]
def map = list.toSpreadMap()
assert 2 == map.size()
assert 'packers' == map['green bay']
}
Output
[green bay:packers, cincinnati:bengals]