0

I cant find a java version of this anywhere. In js this is simple. I have a list of objects with attributes and I want to create arrays for each attribute. The user class simply initializes its own attributes. The main class initializes the list with user objects and then creates lists of usernames and passwords.

User:

public class User{

    String username, password;

    public User(){}

    public User(String myName, String myPwd){

        username = myName;
        password = myPwd;
    }
}

Main:

import java.util.stream.Collectors;

public class Main{

    public static void main(String[] args){

        List<User> users = new ArrayList<>();

        int i = 0;
        while(i<5){

            users.add(new User("Brandon" + i,"LetsGo" + i));
            i++
        }

        System.out.println("Enter your username.");
                String username = scanner.nextLine();
                System.out.println("Enter your password.");
                String password = scanner.nextLine();
        
        //how do I make these lists?
        List<String> names = users.stream().map(User::username).collect(Collectors.toList());
        List<String> pwds = users.stream().map(User::password).collect(Collectors.toList());

        if(names.contains(username)){
            if(pwds.contains(password)){
                System.out.println("Welcome back " + username);
            }else{
                System.out.println("The credentials do not match our records.");
            }
        }else{
            users.add(new User(username, password));
            System.out.println("Welcome " + username);
        }
    }
}   
2
  • 1
    Always search Stack Overflow thoroughly before posting. Commented Feb 23, 2022 at 2:27
  • thanks, I did search far and wide and not just on this site Commented Feb 23, 2022 at 2:30

1 Answer 1

2
  • First, create the user instance with the loop.
List<User> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
  System.out.println("Enter your username.");
  String username = scanner.nextLine();
  System.out.println("Enter your password.");
  String password = scanner.nextLine();
  list.add(new User(username, password));
}
  • Then stream the list like your doing.
List<String> names = users.stream().map(User::username).collect(Collectors.toList());
List<String> pwds = users.stream().map(User::password).collect(Collectors.toList());

But your using a method reference for a getter so you need to include a method username() in your class definition that returns a String. Same for username. These are normally prefixed with get like getUsername.

public String getUsername() {
    return username;
}

Then you can do what you want with the lists

Sign up to request clarification or add additional context in comments.

1 Comment

ahhh getters of course, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.