.... is there a shorter or more efficient way
So you are looking for a more efficient way to do this:
List<String> names = new ArrayList<String>(); for( Customer customer : yourCustomerList ) { names.add( customer.getName() ); }
? !!!!
Or just another way?
All previous answers are not more efficient in terms of runtime and coding. They are, however, more flexible.
Another alternative might be to include Scala Groovy in your Java code and use this:
list.map( _.name ) hit>
list.collect { it.name }
If compiled, Groovy classes can be used with Java, or you can connect them as a script.
Here's a sample for this Customer class, using Groovy as a script.
List<Customer> customers = Arrays.asList( new Customer[]{ new Customer("A","123",1), new Customer("B","456",2), new Customer("C","789",3), new Customer("D","012",4) }); setVariable(customers, "list"); evaluate("names = list.collect { it.name } "); List<String> names = (List<String>) getVariable("names"); System.out.println("names = " + names);
Output:
names = [A, B, C, D]
note: I extracted the method for readability, but you can see them below
But again, this is just different, no more effective than regular for the cycle.
Here is the complete source code . To run, you just need Java1.6 and Groovy in the classpath.
OscarRyz
source share