Search code examples
ballerinaballerina-swan-lake

How to use the `map` function with a ballerina stream?


I have a stream of person records. I need to convert this to a stream of employee records. How can I achieve this using the map function?

The type definition are as below.

type Person record {|
    string name;
    int age;
|};

type Employee record {|
    string name;
    string company;
|};

Solution

  • You need to perform a similar operation as with other map functions.

    Person[] persons = [{name: "John", age: 30}, {name: "Mary", age: 25}];
    
    // convert the array to a stream
    stream<Person> personStream = persons.toStream();
    
    // map each person to an employee and create a new stream of employees
    stream<Employee> employeeStream = personStream.'map(function (Person p) returns Employee {
       Employee e = {
          name: p.name,
          company: "WSO2"  
       };
       return e;
    });
    

    Also you can always refer to the ballerina API docs as well. Here the API docs link.

    Another thing that will help is you can hover your cursor on the map function and you can see function definition along with examples. Here is SS of what I have mentioned.

    hover on map function