如何在列表的每个元素上调用方法? [英] How can I call a method on each element of a List?

查看:93
本文介绍了如何在列表的每个元素上调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有汽车清单:

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

如何缩短上面的代码?概括地说,如何在List的每个元素上调用方法?

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

例如,在Python中:

For example, in Python :

[car.name for car in cars]

推荐答案

更新:

有关使用lambda表达式的Java 8解决方案,请参见aaiezza的答案.

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

Java 8之前的原始答案:

使用Guava可以实现效果,Function实现已经比您拥有的更加冗长:

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

因此,这并不能帮助您缩短代码,但这是在Java中达到所需效果的详细说明.

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.

编辑:您可能会看到 lambdaj ,一个库似乎可以满足您的需求.我还没有亲自尝试过,但是首页显示了以下示例:

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

这篇关于如何在列表的每个元素上调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆