我有一个对象类型的列表,说客户类(属性:customerId,customerName)和一个字符串数组。
有什么方法可以使用列表中的所有customerName填充/获取数组吗? (手动遍历列表除外)
即
Customer c1 = new Customer(1,"ABC");
Customer c2 = new Customer(2,"DEF");
Customer c3 = new Customer(3,"XYZ");
List<Customer> list = new ArrayList<Customer>();
list.put(c1); list.put(c2); list.put(c3);
String[] allCustomerNames = new String[list.size()];
//Code to get allCustomerNames populated.
//Ofcourse, other than to iterate through list
有什么办法类似于...
allCustomerNames = list.toArray(customerNameConvertor);
其中,customerNameConveror是假设的转换程序类,该类将告知将customerName用于数组元素的填充。
最佳答案
您可以使用第三方库(例如Guava或F4J)来完成此操作。
这就是在番石榴中的样子:
Function<Customer, String> customerToName = new Function<Customer, String>() {
public String apply(Customer c) {
return c.getName();
};
List<String> allCustomerNamesList = Lists.transform(list, customerToName);
如果需要数组,则必须使用常规的toArray方法:
allCustomerNames = allCustomerNamesList.toArray(allCustomerNames);
关于java - 用于将java.util.list转换为数组的客户转换程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14209399/