我有一个对象类型的列表,如Customer类(属性:customerId,customerName)和一个String数组。
有没有办法从列表中填充/获取包含所有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来表示数组元素的数量。
答案 0 :(得分:5)
这就是Guava的样子:
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);
答案 1 :(得分:1)
您可以编写这样的实用程序类。您可以获得所有字段的值数组。
public class FieldToArrayConvertor {
public static Object[] getFieldValuesFromEntityList(List list, String fieldName) throws Exception {
Object[] array = new Object[list.size()];
int i=0;
for(Object o : list) {
Class<? extends Object> aClass = o.getClass();
Field field = aClass.getDeclaredField(fieldName);
Object invoke = field.get(o);
array[i]= invoke;
i++;
}
return array;
}
public static void main(String[] args) {
try {
Employee em = new Employee("emp1");
Employee em1 = new Employee("emp2");
List<Employee> list1= new ArrayList() ;
list1.add(em);
list1.add(em1);
Object[] field = getFieldValuesFromEntityList(list1, "name");
for(Object o: field) {
System.out.println(o);
}
} catch (Exception ex) {
Logger.getLogger(FieldToArrayConvertor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
另请参阅: Uses of Reflection