-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));
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 Commented Sep 15, 2021 at 8:14
  • As an aside, don't call variables var. It's now a sort-of keyword, and may be misinterpreted by readers. Commented Sep 15, 2021 at 8:15

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.