Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a method on each element of a List?

Suppose that I have a list of cars :

public class Car {     private String brand;     private String name;     private String color;      public Car() { // ...  }      public getName() { return name; }     // ... } 

// Suppose that I have already init the list of car List<Car> cars = //... List<String> names = new ArrayList<String>();   for (Car c : cars ) {     names.add(c.getName()); } 

How can I shorten the code above ? In a nutshell, How can I call a method on each element of a List ?

For example, in Python :

[car.name for car in cars] 
like image 526
Sandro Munda Avatar asked Aug 28 '11 15:08

Sandro Munda


People also ask

How do you call a method from a list in Java?

Original pre-Java 8 answer: List<Car> cars = //... Function<Car, String> carsToNames = new Function<Car, String>() { @Override public String apply(Car car) { return car. getName(); } } List<String> names = Lists. transform(cars, carsToNames);

How do you apply an operation to each element in a list Python?

Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.

How do you call a collection method in Java?

Calling Static Method in Java All the methods that have static keyword before the method name are known as static methods. We can also create a static method by using the static keyword before the method name. We can call a static method by using the ClassName. methodName.

What method is used to get the number of elements in a list in Java?

The size of an ArrayList can be obtained by using the java. util. ArrayList. size() method as it returns the number of elements in the ArrayList i.e. the size.


2 Answers

Java 8 will (hopefully) have some form of lambda expression, which will make code like this more feasible. (Whether there'll be anything like list comprehensions is another matter.)

Your wish has been granted!

---EDIT---
lol as if on cue: forEach()

Definitely check this out.

For your question specifically, it becomes the folowing:

// Suppose that I have already init the list of car List<Car> cars = //... List<String> names = new ArrayList<String>();  // LAMBDA EXPRESSION cars.forEach( (car) -> names.add(car.getName()) ); 

It's really quite incredible what they've done here. I'm excited to see this used in the future.

---EDIT---
I should have seen this sooner but I can't resist but to post about it.

The Stream functionality added in jdk8 allows for the map method.

// Suppose that I have already init the list of car List<Car> cars = //...  // LAMBDA EXPRESSION List<String> names = cars.stream().map( car -> car.getName() ).collect( Collectors.toList() ); 

Even more concise would be to use Java 8's method references (oracle doc).

List<String> names = cars.stream().map( Car::getName ).collect( Collectors.toList() ); 
like image 76
aaiezza Avatar answered Sep 28 '22 08:09

aaiezza


UPDATE:

See aaiezza's answer for a Java 8 solution using a lambda expression.

Original pre-Java 8 answer:

The effect can be achieved with Guava, the Function implementation is already more verbose than what you have:

List<Car> cars = //...  Function<Car, String> carsToNames = new Function<Car, String>() {    @Override    public String apply(Car car) {       return car.getName();    } }  List<String> names = Lists.transform(cars, carsToNames); 

(Keep in mind that Lists.transform returns a view that will apply the function lazily - if you want an immediate copy, you need to copy the returned list into a new list.)

So this doesn't help you shorten your code, but it's an example of how verbose it is to achieve your desired affect in Java.

Edit: You might have a look at lambdaj, a library that seems to approach what you're looking for. I haven't tried this out myself, but the homepage shows this example:

List<Person> personInFamily = asList(new Person("Domenico"), new Person("Mario"), new Person("Irma")); forEach(personInFamily).setLastName("Fusco"); 
like image 24
Paul Bellora Avatar answered Sep 28 '22 10:09

Paul Bellora