-1

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));
Askabius
  • 3
  • 2
  • 1
    you should also learn basic Java. that is not how you compare the value of Strings (or any type of object) in Java – Stultuske Sep 15 '21 at 08:14
  • As an aside, don't call variables `var`. It's now a sort-of keyword, and may be misinterpreted by readers. – Andy Turner Sep 15 '21 at 08:15

1 Answers1

0

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));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243