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

Match the id from List and get the String – Java

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?

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

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;
    }
}

>Solution :

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