-3

I have made a class called User with two string attributes: Login and Password.

I have a database (userList, of type ArrayList<User>) with all the existing users, and I want to know if a login is already used or not.

I tried to use lambda expressions in order to do that, but it doesn't work:

ArrayList<String> loginList = null;
userListe.forEach(x->loginList.add(x.getLogin()));

How do I solve this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pierre I
  • 61
  • 5

1 Answers1

0

Assuming userListe is a List:

List<String> loginList = userListe
             .stream()
             .map(x -> x.getLogin())
             .collect(Collectors.toList));

Explanation:

It is better to use a List instead of ArrayList because it is always preferable using interface instead of concrete types. First, using a stream you create a flow of User objects. Using map you get a field from your objects using the appropriate getter. At last, using a collect you can collect all objects returned by map method, in this case String object.

Your loginList is null, so the first forEach will throw a NullPointerException. Also, remember that it is better to have pure function in lambdas, with no side effects. Using stream and collect allows you to get a List of objects you need without having functions with side effects.

Lorelorelore
  • 3,335
  • 8
  • 29
  • 40