Home > Net >  Match the id from List and get the String - Java
Match the id from List and get the String - Java

Time:04-26

I have to get UserName -> firstname and lastname where the id matches to UserIN list.

I dont know how to exactly do this, i think that for loop is bad, and we could do this by Collecions to avoid bad implementations.

Any solutions?

UserIN class:

public class UserIN {
    int id;
    UserName name;


    @Override
    public String toString() {
        return "UserIN{"  
                "id="   id  
                ", name="   name  
                '}';
    }

    public UserIN(int id, UserName name) {
        this.id = id;
        this.name = name;
    }
    // getters & setters here
}

UserName class:

public class UserName {
    String firstname;
    String lastname;

    @Override
    public String toString() {
        return "UserName{"  
                "firstname='"   firstname   '\''  
                ", lastname='"   lastname   '\''  
                '}';
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public UserName() {}

    public UserName(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
}

CodePudding user response:

If you want to avoid a loop, you can use a Map

import java.util.*;

...

// Maps user ids (integer) to UserName objects:
Map<Integer, UserName> map = new HashMap<>();

// Create two users and put them in the map:
UserIN user0 = new UserIN(0, new UserName("Peter", "Woodbridge"));
UserIN user1 = new UserIN(1, new UserName("Anne", "Miller"));
map.put(user0.id, user0.name);
map.put(user1.id, user1.name);

// Get user with id==1 from the map and print it to standard output
UserName user = map.get(1);
System.out.println(user.firstname   " "   user.lastname); 

This prints:

Anne Miller
  • Related