Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading