ballerinaballerina-swan-lake

Find intersection of 2 arrays in Ballerina


I have 2 arrays (batsmen and bowlers). Whats the best way to find the intersection of these and create the allrounders array?

public type Player record {
    int id;
    string name;
};

Player[] batsmen = [
    {id: 1, name: "Virat"},
    {id: 2, name: "Rohit"},
    {id: 3, name: "Jadeja"}
];

Player[] bowlers = [
    {id: 3, name: "Jadeja"},
    {id: 4, name: "Bumrah"},
    {id: 5, name: "Shami"}
];

Player[] allrounders = [];

Solution

  • import ballerina/io;
    public type Player record {
        int id;
        string name;
    };
    
    Player[] batsmen = [
        {id: 1, name: "Virat"},
        {id: 2, name: "Rohit"},
        {id: 3, name: "Jadeja"}
    ];
    
    Player[] bowlers = [
        {id: 3, name: "Jadeja"},
        {id: 4, name: "Bumrah"},
        {id: 5, name: "Shami"}
    ];
    
    Player[] allrounders = [];
    public function main() {
        allrounders = from Player batsman in batsmen join Player bowler in bowlers on batsman.id equals bowler.id
        select batsman;
        io:println(allrounders);
    }
    

    You can find more details on join in here https://ballerina.io/learn/by-example/outer-join-clause/