javaoopstrong-typing

"Bad return type in lambda expression: String cannot be converted to void" in .forEach method


I have a class Users with, among others, a List of user objects, the following method, which is supposed to

  1. build a list of String
  2. check if an incoming String is contained in that list.
public class Users {
    List<User> users;

    public Users(List<User> users) {
        this.users = new ArrayList<>();
    }

    #...

    public boolean checkUserExists(String targetUserID) {
        List<String> userIDS = users.forEach(user -> user.userID);
        return userIDS.contains(targetUserID);
    }
}

But, under the lambda expression, SonarLint shows the "Bad return type in lambda expression: String cannot be converted to void" error.

This is how the class User is implemented:

package menus.DataStructures;

public class User {
    String userType;
    String userID;
    String userName;
    int userAge;

    protected User(String userType, String userID, String userName, int userAGe) {
        this.userType = userType;
        this.userID = userID;
        this.userName = userName;
        this.userAge = userAGe;
    }
}

In my mind, there shouldn't be a problem, but I'm almost new to Java and I come from JS and Python. I have read answers addressing the same error message but due to my Java ignorance I haven't been able to understand anything.

What causes this error?


Solution

  • It looks like what you're looking for is map and not forEach:

    public boolean checkUserExists(String targetUserID) {
        List<String> userIDS = users.stream().map((user) -> user.userID).collect(Collectors.toList()) 
        // if you're using java 16+ you can replace .collect(...) with .toList();
        return userIDS.contains(targetUserID);
    }