Home > Software design >  How to get value from List<> giving String as variable name [duplicate]
How to get value from List<> giving String as variable name [duplicate]

Time:09-17

I have a list based on database.

List<Contact> contactList;

There are many variables. For example:

String name;
String phone;

Can I get a specific value in way like this?

String var = "name";
String val = contactList.get(0).var <--- this Sting variable here 

Is any way to do something like this? I don't want to write x10 :

if(var == "name"){
 String val = contactList.get(0).name;
}

I think is way for do it, but I'm newbie, sorry if something is wrong with my question. I will be very grateful for help.


Working code:

Thank you for answer. This is full code if someone will be looking for answer in the future:

private Map<String, Function<Contact, String>> map;



map = new HashMap<>();
map.put("Name", c -> c.name);
map.put("Phone", c -> c.phone);
map.put("Email", c -> c.email);  

String some_val = map.get(second_value).apply(contactList.get(position));

CodePudding user response:

You need a Map<String, Function<Contact, String>> containing method references, keyed by the property name.

For example:

// Construct this once, store in a static final field.
Map<String, Function<Contact, String> map =
    Map.of("name", c -> c.name /* etc for other fields */);

// Then, when you want to get the value:
String val = map.get(var).apply(contactList.get(0));
  • Related