首页 > 解决方案 > 如何从 List<> 中获取值,将 String 作为变量名

问题描述

我有一个基于数据库的列表。

List<Contact> contactList;

有很多变数。例如:

String name;
String phone;

我可以以这样的方式获得特定的价值吗?

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

有什么办法可以做这样的事情吗?我不想写 x10 :

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

我认为这样做是可行的,但我是新手,如果我的问题有问题,我很抱歉。我将非常感谢您的帮助。


工作代码:

谢谢你的答案。如果将来有人要寻找答案,这是完整的代码:

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

标签: javaandroidlist

解决方案


您需要一个Map<String, Function<Contact, String>>包含方法引用,以属性名称为键。

例如:

// 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));

推荐阅读