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

前端 未结 6 1105
太阳男子
太阳男子 2020-12-09 14:41

Suppose that I have a list of cars :

public class Car {
    private String brand;
    private String name;
    private String color;

    public Car() { // .         


        
6条回答
  •  孤街浪徒
    2020-12-09 15:29

    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 cars = //...
    List names = new ArrayList();
    
    // 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 cars = //...
    
    // LAMBDA EXPRESSION
    List 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 names = cars.stream().map( Car::getName ).collect( Collectors.toList() );
    

提交回复
热议问题