Simplify method using lambda expressions

2

I have this simple method:

public void setComboBoxItems(List<User> users, List<Client> clients) {
    for (User user : users) {
        usersIds.addItem(user.getId());
    }

    for (Client client : clients) {
        clientsIds.addItem(client.getId());
    }
}

What it does is add items to 2 JComboBox , the items added are the ID of the Users and Clients contained in the 2 lists of name users- clients .

Is there any way to simplify this method, maybe by calling users.forEach() ?

    
asked by Bryan Romero 15.12.2018 в 17:49
source

1 answer

1

My goal was to have fewer lines of code and do it with lambda expressions, so what I did was use .forEach .

public void setComboBoxItems(List<User> users, List<Client> clients) {
    users.forEach(user -> usersIds.addItem(user.getId()));
    clients.forEach(client -> clientsIds.addItem(client.getId()));
}

That does practically the same as the previous method.

Let's say you could have done something like this:

public void setComboBoxItems(List<User> users, List<Client> clients) {
    for (User user : users) {usersIds.addItem(user.getId());}
    for (Client client : clients) {clientsIds.addItem(client.getId());}
}

The same code as before but trying to save space but it's not what I'm looking for since my goal is to learn and make use of lambda expressions.

    
answered by 16.12.2018 / 16:36
source