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);
        }
    }
}   
MVB76
  • 149
  • 7
  • 1
    Always [search Stack Overflow](https://duckduckgo.com/?q=site%3Astackoverflow.com+java+make+arrays+from+properties&t=osx&ia=web) thoroughly before posting. – Basil Bourque Feb 23 '22 at 02:27
  • thanks, I did search far and wide and not just on this site – MVB76 Feb 23 '22 at 02:30

1 Answers1

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

WJS
  • 36,363
  • 4
  • 24
  • 39